/
a4.py
284 lines (256 loc) · 8.96 KB
/
a4.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
import networkx as nx
inputFile = 'all_in.txt'
'''
Getting raw input
////////////////////////////////////////////////////////
'''
rawInputArray = []
with open(inputFile) as f:
for line in f:
rawInputArray.append(line.split())
'''
////////////////////////////////////////////////////////
End raw input
'''
'''
Parsing input into graphs
////////////////////////////////////////////////////////
'''
# all arrays map 1-1 to each other, and hold graphs, budgets, and host Id's respectively
testCaseGraphs = []
testCaseBudgets = []
testCaseHostIDs = []
# number of test cases is always first line of input
numOfTestCases = int(rawInputArray[0][0])
# we will iterate in such a way that the value of lineNum always
# represents a line number that gives test case specifications
# we init is as 1 to start from the second line (since the first line specifies # of test cases)
lineNum = 1
for i in range(numOfTestCases):
#print("test case " + str(i + 1))
G = nx.Graph()
# get int values from the line
#print(rawInputArray[lineNum])
numberOfLinks = int(rawInputArray[lineNum][1])
numberOfParties = int(rawInputArray[lineNum][2])
numberOfHosts = int(rawInputArray[lineNum][3])
testCaseBudgets.append(numberOfParties)
# slice array from first friendship link to last friendship link
testCaseLinkSlice = rawInputArray[lineNum + 1:(lineNum + numberOfLinks + 1)]
linkSliceLength = len(testCaseLinkSlice)
# creating graphs and appending to graph array
for j in range(linkSliceLength):
person1 = testCaseLinkSlice[j][0]
person2 = testCaseLinkSlice[j][1]
#print(person1 + " " + person2)
# add to graph
G.add_edge(person1, person2)
G.add_node(person1, depth=-1)
G.add_node(person2, depth=-1)
testCaseGraphs.append(G)
# moving to lines that specify host id's
lineNum += (numberOfLinks + 1)
testCaseHostSlice = rawInputArray[lineNum:(lineNum + numberOfHosts)]
hostSliceLength = len(testCaseHostSlice)
# appending host id's to array
hostIds = []
for k in range(hostSliceLength):
hostIds.append(testCaseHostSlice[k][0])
#print(testCaseHostSlice[k][0])
testCaseHostIDs.append(hostIds)
# moving to next line that has test case specifications
lineNum += numberOfHosts
#print("End test case")
'''
////////////////////////////////////////////////////////
End Parsing
'''
'''
Utilities
////////////////////////////////////////////////////////
'''
'''
numberOfNeighbors
Returns number of neighbors -_-
'''
def numberOfNeighbors(graph, root):
return len(list(nx.all_neighbors(graph, root)))
'''
mostNeighbors
Returns the node with most neighbors
'''
def mostNeighbors(graph):
maxNeighbors = 0
retNode = None
for node in graph.nodes:
if numberOfNeighbors(graph, node) > maxNeighbors:
maxNeighbors = numberOfNeighbors(graph, node)
retNode = node
# break ties by lower ID
elif numberOfNeighbors(graph, node) == maxNeighbors:
if (node < retNode):
retNode = node
return retNode
'''
mostAwkward
Returns the most awkward (highest depth) node
'''
def mostAwkward(graph):
maxAwkward = 0
retNode = None
for node in graph.nodes:
if graph.nodes[node]["depth"] > maxAwkward:
maxAwkward = graph.nodes[node]["depth"]
retNode = node
# break ties by lower ID
elif graph.nodes[node]["depth"] == maxAwkward:
if (node < retNode):
retNode = node
return retNode
'''
setNodeDepths
Sets node depth on a graph for every node from root.
Since this function modifies the given graph, it is important to
work with copies if working on the same graph more than once
'''
def setNodeDepths(graph, root):
for node in graph.nodes:
shortestPath = nx.shortest_path_length(graph, source=root, target=node)
# -1 is what all node depths are initialized at
# if depth is == -1 then we just set it to the shortestPath
if (graph.nodes[node]["depth"] == -1):
graph.nodes[node]["depth"] = shortestPath
# elif there is an actual value and we need to check if the new shortestPath
# is less than it
elif (shortestPath < graph.nodes[node]["depth"]):
graph.nodes[node]["depth"] = shortestPath
'''
sumOfDepths
Sum of all node depths
'''
def sumOfDepths(graph):
sumOfDepths = 0
for node in graph.nodes:
sumOfDepths += float(graph.nodes[node]["depth"])
return sumOfDepths
'''
computeSocialAwkwardness
Compute social awkwardness for the case that M hosts are given
'''
def computeSocialAwkwardness(graph, hostIds):
for id in hostIds:
setNodeDepths(graph, id)
return '{:.2f}'.format(round((sumOfDepths(graph) / (nx.number_of_nodes(graph) - len(hostIds))), 2))
'''
mostUniqueFriends
Find the node with most unique vertices
'''
def mostUniqueFriends(graph, adjacents):
max = 0
maxNode = None
for node in graph.nodes:
uniqueFriends = 0
for v in list(nx.all_neighbors(graph, node)):
if v not in adjacents:
uniqueFriends += 1
if uniqueFriends > max:
max = uniqueFriends
maxNode = node
return maxNode
'''
////////////////////////////////////////////////////////
End Utilities
'''
'''
Heuristics for Part 4
////////////////////////////////////////////////////////
'''
'''
assignmentHeuristicOne
Find the person with the most friends and make them a party host. Repeat until M
party hosts have been assigned. Ties should be resolved by choosing the person with a
lower numerical ID.
'''
def assignmentHeuristicOne(graph, budget):
nodes = list(graph.nodes)
# python sort is stable so sort by id, then by number of neighbors
nodes.sort(key=lambda x: int(x), reverse=False)
nodes.sort(key=lambda x: numberOfNeighbors(graph, x), reverse=True)
return nodes[:budget]
'''
assignmentHeuristicTwo
First pick the person with the most friends and make them a party host. On subsequent
rounds, find the person with the maximum current social awkwardness and make
them a party host. Repeat until M party hosts have been assigned. Ties should be
resolved by choosing the person with a lower numerical ID.
'''
def assignmentHeuristicTwo(graph, budget):
# use a local copy since setNodeDepths() modifes given graph
localGraphCopy = graph
hosts = []
hosts.append(mostNeighbors(localGraphCopy))
while len(hosts) < budget:
setNodeDepths(localGraphCopy, hosts[len(hosts) - 1])
hosts.append(mostAwkward(localGraphCopy))
return hosts
'''
myHeuristic
Continuously pick a host who shares the least vertices (friends) with the other hosts.
So we will have hosts with the maximum amount of unique neighbors.
'''
def myHeuristic(graph, budget):
hosts = []
# a set of nodes that are adjacent to a host
adjacents = set([])
while len(hosts) < budget:
v = mostUniqueFriends(graph, adjacents)
if v not in hosts:
for neighbor in list(nx.all_neighbors(graph, v)):
adjacents.add(neighbor)
adjacents.add(v)
hosts.append(v)
return hosts
'''
////////////////////////////////////////////////////////
End Heuristics
'''
'''
Writing output
////////////////////////////////////////////////////////
'''
def writeHeuristicOne(output,graph, budget):
hcopy = graph.copy()
heuristicOneHostIds = assignmentHeuristicOne(hcopy, budget)
output.write("Heuristic 1 hosts are ")
output.write(','.join(heuristicOneHostIds) + "\n")
output.write("Average social awkwardness = ")
output.write(str(computeSocialAwkwardness(hcopy, heuristicOneHostIds)) + "\n")
def writeHeuristicTwo(output,graph, budget):
hcopy = graph.copy()
heuristicTwoHostIds = assignmentHeuristicTwo(hcopy, budget)
output.write("Heuristic 2 hosts are ")
output.write(','.join(heuristicTwoHostIds) + "\n")
output.write("Average social awkwardness = ")
output.write(str(computeSocialAwkwardness(hcopy, heuristicTwoHostIds)) + "\n")
def writeMyHeuristic(output, graph, budget):
hcopy = graph.copy()
myHeuristicHostIds = myHeuristic(hcopy, budget)
output.write("My heuristic hosts are ")
output.write(','.join(myHeuristicHostIds) + "\n")
output.write("Average social awkwardness = ")
output.write(str(computeSocialAwkwardness(hcopy, myHeuristicHostIds)) + "\n")
output = open("output.txt", "w")
for i, graph in enumerate(testCaseGraphs):
output.write("Test Case " + str(i+1) + ".\n")
if len(testCaseHostIDs[i]) == 0:
writeHeuristicOne(output, testCaseGraphs[i], testCaseBudgets[i])
writeHeuristicTwo(output, testCaseGraphs[i], testCaseBudgets[i])
writeMyHeuristic(output, testCaseGraphs[i], testCaseBudgets[i])
elif len(testCaseHostIDs[i]) >= 1:
output.write("Average social awkwardness = ")
output.write(str(computeSocialAwkwardness(testCaseGraphs[i], testCaseHostIDs[i])))
output.write("\n")
'''
////////////////////////////////////////////////////////
End writing
'''