Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitd1e64ed

Browse files
committed
Google challenge level 4, first part.
Revised theory and came up with a basic concept of algorithm.
1 parent608ef04 commitd1e64ed

File tree

10 files changed

+237
-53
lines changed

10 files changed

+237
-53
lines changed

‎src/google/Level4/Challenge1/README.md‎

Lines changed: 81 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ You and your rescued bunny prisoners need to get out of this collapsing death tr
77

88
The**time it takes to move** from your starting point to all of the bunnies and to the bulkhead will be given to you in a square matrix of integers.**Each row will tell you the time it takes to get to the start, first bunny, second bunny, ..., last bunny, and the bulkhead in that order**. The order of the rows follows the same pattern (start, each bunny, bulkhead). The bunnies can jump into your arms, so picking them up is instantaneous, and arriving at the bulkhead at the same time as it seals still allows for a successful, if dramatic, escape. (Don't worry, any bunnies you don't pick up will be able to escape with you since they no longer have to carry the ones you did pick up.) You can revisit different spots if you wish, and moving to the bulkhead doesn't mean you have to immediately leave -**you can move to and from the bulkhead to pick up additional bunnies if time permits**.
99

10-
In addition to spending time traveling between bunnies, some paths interact with the space station's security checkpoints and add time back to the clock. Adding time to the clock will delay the closing of the bulkhead doors, and if the time goes back up to 0 or a positive number after the doors have already closed, it triggers the bulkhead to reopen. Therefore, it might be possible to walk in a circle and keep gaining time: that is**each time a path is traversed, the same amount of time is used or added**.
10+
In addition to spending time traveling between bunnies, some paths interact with the space station's security checkpoints and**add time back to the clock**. Adding time to the clock will delay the closing of the bulkhead doors, and if the time goes back up to 0 or a positive number after the doors have already closed, it**triggers the bulkhead to reopen**. Therefore, it might be possible to walk in a circle and keep gaining time: that is**each time a path is traversed, the same amount of time is used or added**.
1111

1212
Write a function of the form solution(times, time_limit) to calculate the most bunnies you can pick up and which bunnies they are, while still escaping through the bulkhead before the doors close for good. If there are multiple sets of bunnies of the same size,**return the set of bunnies with the lowest prisoner IDs (as indexes) in sorted order**. The bunnies are represented as a sorted list by prisoner ID, with the**first bunny being 0**.There are at most**5 bunnies**, and time_limit is a non-negative integer that is at most***999**.
1313

@@ -70,7 +70,7 @@ Use verify [file] to test your solution and see how it does. When you are finish
7070

7171
##First Analysis
7272

73-
###Provided Case 1
73+
###Provided Case 1: Time Added Back
7474
Time Limit: 1
7575
Answer: Bunnies 1, 2
7676

@@ -84,21 +84,22 @@ Answer: Bunnies 1, 2
8484
Start End Delta Time Status
8585
- 0 - 1 // Bulkhead initially open
8686

87-
0 4 -1 2 // Add time. As the minimal time needed is 2 to rescuse any bunny,it is optedto add more time. And to add time we can jumptoBulkhead once.
87+
0 4 -1 2 // Add time. As the minimal time needed is 2 to rescuse any bunny,we needto add1more time which can be gained by opening Bulkhead as 0to4 is -1.
8888

89-
4 2 2 0 // Rescue a bunny. As there are bunnies those requires time which we have gathered, i.e. 2, it is opted to rescue Bunny 1.
89+
4 2 2 0 // Rescue a bunny. As there are bunnies those requires time which we have gathered, i.e. 2, it is opted to rescue Bunny 1.
9090

91-
2 4 -1 1 // Add time.Now rescue more bunny we needtoget more time so weneed togo throughbulkhead again.
91+
2 4 -1 1 // Add time.Although we can exit at this point but goingtoBulhead add timebackso we go throughit.
9292

93-
4 3 2 -1 //Go to secondbunny as the time taken is 2,we will have to 1 timetogive back. We can not go to first bunny as it takes 3 to carry bunny and we will not be able to reopen the bulkhead.
93+
4 3 2 -1 //Future calculation. Rescue Secondbunny as the time taken is 2,and from there is pathtoBulkhead which adds back time while going through.
9494

95-
3 4 -1 0 Open bulkhead. Exit. As reopening bulkhead add 1, we can return the time we lended, i.e. -1.
95+
3 4 -1 0 // Exit. The last Third bunny is left to rescue but as the time is 0 we will not be able to rescue it.
96+
9697

9798
>What if I try to recuse all of the bunnies?
9899
99100

100101

101-
###Provided Case 2
102+
###Provided Case 2: No Time Added Back
102103

103104
Time Limit: 3
104105
Answer: Bunnies 0, 1
@@ -112,9 +113,9 @@ Answer: Bunnies 0, 1
112113

113114
Start End Delta Time Status
114115
- 0 - 3 Bulkhead is open
115-
0 1 2 2 Rescuebunny one
116-
1 2 1 1 Rescuebunny two
117-
2 4 0 0 Exit. We can go directly to 4 as it takes 1 time to open the bulkhead.
116+
0 1 2 2 RescueFirst Bunny.
117+
1 2 1 1 RescueSecond Bunny.
118+
2 4 0 0 Exit.
118119

119120
If we wanted to rescue third bunny then we needed to add more time, which is slows the process, so we skip them as the requirement to the problem was to be fast! But there could have been another solution to rescue 0,3 0r 1,3 bunny as well as every rescure needs exactly same time.
120121

@@ -420,3 +421,72 @@ From the research solution could be found in the following steps:
420421
-[ ] Understand and implement the finding number 3.
421422
-[ ] Reviewhttps://iq.opengenus.org/blossom-maximum-matching-algorithm
422423
-[ ] Reviewhttps://www.informit.com/articles/article.aspx?p=169575&seqNum=8
424+
425+
426+
###Third Analysis
427+
Went back to the problem and update the description to the given examples above.
428+
429+
####Some Theory
430+
431+
>Graph representations
432+
Adjacency Matrix is a n-by-n matrix with A uv = 1 if (u, v) is an edge.
433+
- Two representations of each edge.
434+
- Space proportional to n 2 .
435+
- Checking if (u, v) is an edge takes Θ(1) time.
436+
- Identifying all edges takes Θ(n 2 ) time.
437+
438+
Adjacency Lists is a node-indexed array of lists.
439+
- Two representations of each edge.
440+
- Space is Θ(m + n).
441+
- Checking if (u, v) is an edge takes O(degree(u)) time. degree = number of neighbors of u.
442+
- Identifying all edges takes Θ(m + n) time.
443+
444+
445+
Cycles: A cycle is a path v 1 , v 2 , ..., v k in which v 1 = v k and k ≥ 2.
446+
Trees: An undirected graph is a tree if it is connected and does not contain a cycle.
447+
448+
Shortest path problem. Given two nodes s and t, what is the length of a shortest path between s and t?
449+
450+
**In our problem we intend to return the nodes which can be reached with the time we have.**
451+
452+
Breadth-first search: Explore outward from s in all possible directions, adding nodes one “layer” L at a time.
453+
BFS algorithm.
454+
- L0 = {s}
455+
- L1 = all neighbors of L0
456+
- L2 = all nodes that do not belong to L0 or L1 , and that have an edge to a node in L1
457+
- Li+1 = all nodes that do not belong to an earlier layer, and that have an edge to a node in Li
458+
459+
BFS runs in O(m + n) time if the graph is given by an adjacency representation.
460+
461+
Connected component. Find all nodes reachable from a point.
462+
463+
**This kind of represents our problem** - Which nodes can can we reach from start with the limited time constraints.
464+
465+
>Graph search
466+
- Directed reachability. Given a node s, find all nodes reachable from s.
467+
- Directed s↝t shortest path problem. Given two nodes s and t, what is the length of a shortest path from s to t?
468+
- Graph search. BFS extends naturally to directed graphs.
469+
470+
>Strong connectivity
471+
- Def. Nodes u and v are mutually reachable if there is both a path from u to v and also a path from v to u.
472+
- Def. A graph is strongly connected if every pair of nodes is mutually reachable.
473+
474+
>Directed acyclic graphs
475+
- Def. A DAG is a directed graph that contains no directed cycles.
476+
- Def. A topological order of a directed graph G = (V, E) is an ordering of its nodes as v 1 , v 2 , ..., v n so that for every edge (v i , v j ) we have i < j.
477+
478+
>Cycles
479+
Def. A path is a sequence of edges which connects a sequence of nodes.
480+
Def. A cycle is a path with no repeated nodes or edges other than the starting and ending nodes.
481+
482+
>Minimum spanning tree (MST)
483+
Def. Given a connected, undirected graph G = (V, E) with edge costs ce, a minimum spanning tree (V, T ) is a spanning tree of G such that the sum of the edge costs in T is minimized.
484+
485+
>Arborescence
486+
In graph theory, an arborescence is a directed graph in which, for a vertex u called the root and any other vertex v, there is exactly one directed path from u to v. An arborescence is thus the directed-graph form of a rooted tree, understood here as an undirected graph. Equivalently, an arborescence is a directed, rooted tree in which all edges point away from the root; a number of other equivalent characterizations exist. Every arborescence is a directed acyclic graph, but not every DAG is an arborescence. An arborescence can equivalently be defined as a rooted digraph in which the path from the root to any other vertex is unique.
487+
488+
>Algorithmic Paradigms:
489+
- Greed: Process the input in some order, myopically making irrevocable decisions.
490+
- Divide-and-conquer: Break up a problem into independent subproblems; Solve each subproblem; Combine solutions to subproblems to form solutionto original problem.
491+
- Dynamic programming: Break up a problem into a series of overlapping subproblems; Combine solutions to smaller subproblems to form solution to large subproblem.Dynamic programming is a fancy name for caching intermediate results in a table for later reuse.
492+
4.59 MB
Binary file not shown.
9.03 MB
Binary file not shown.
14.6 MB
Binary file not shown.
11.3 MB
Binary file not shown.
16.7 MB
Binary file not shown.
9.72 MB
Binary file not shown.
6.47 MB
Binary file not shown.
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
# https://www.techiedelight.com/determine-negative-weight-cycle-graph/
2+
3+
# define infinity as maximum value of the integer
4+
INF=float('inf')
5+
6+
7+
# Function to run Bellman-Ford algorithm from given source
8+
defBellmanFord(edges,source,time):
9+
10+
# cost stores shortest-path information
11+
cost= [time]*N
12+
13+
# Initially all vertices except source vertex have a weight of infinity
14+
cost[source]=0
15+
16+
# Relaxation step (run V-1 times)
17+
for_inrange(N-1):
18+
# consider all edges from u to v having weight w
19+
for (u,v,w)inedges:
20+
# if the cost to the destination u can be
21+
# shortened by taking the edge u -> v
22+
ifcost[u]!=timeandcost[u]+w<cost[v]:
23+
# update cost to the lower value
24+
cost[v]=cost[u]+w
25+
26+
# Run relaxation step once more for N'th time to
27+
# check for negative-weight cycles
28+
for (u,v,w)inedges:
29+
# if the cost to the destination u can be
30+
# shortened by taking the edge u -> v
31+
ifcost[u]!=timeandcost[u]+w<cost[v]:
32+
returnTrue
33+
34+
returnFalse
35+
36+
# returns a List of graph edges
37+
defMakeEdge(adjMatrix):
38+
edges= []
39+
forvinrange(N):
40+
foruinrange(N):
41+
ifadjMatrix[v][u]andadjMatrix[v][u]!=time:
42+
# edge from source v to dest u having specified weight
43+
edges.append((v,u,adjMatrix[v][u]))
44+
45+
returnedges
46+
47+
48+
if__name__=='__main__':
49+
50+
# given adjacency representation of matrix
51+
# adjMatrix = [
52+
# [0, INF, -2, INF],
53+
# [4, 0, -3, INF],
54+
# [INF, INF, 0, 2],
55+
# [INF, -1, INF, 0]
56+
# ]
57+
58+
# adjMatrix = [
59+
# [0, 2, 2, 2, -1],
60+
# [9, 0, 2, 2, -1],
61+
# [9, 3, 0, 2, -1],
62+
# [9, 3, 2, 0, -1],
63+
# [9, 3, 2, 2, 0]
64+
# ]
65+
# # N is number of vertices in the graph
66+
# N = 5
67+
# time = 1
68+
69+
adjMatrix= [
70+
[0,1,1,1,1],
71+
[1,0,1,1,1],
72+
[1,1,0,1,1],
73+
[1,1,1,0,1],
74+
[1,1,1,1,0]
75+
]
76+
N=5
77+
time=3
78+
79+
# # Negative Weight Cycle
80+
# adjMatrix = [
81+
# [0, 3, 1, 8, INF],
82+
# [2, 0, 9, 4, INF],
83+
# [-5, INF, 0, INF, -2],
84+
# [INF, INF, 1, 0, INF],
85+
# [INF, INF, INF, 0, 0]
86+
# ]
87+
# N = 5
88+
# time = 10
89+
90+
91+
92+
edges=MakeEdge(adjMatrix)
93+
94+
# run Bellman-Ford algorithm from each vertex as source
95+
# and check for any Negative Weight Cycle
96+
foriinrange(N):
97+
ifBellmanFord(edges,i,time):
98+
print("Negative Weight Cycle Found!!")
99+
break
100+

‎src/google/Level4/Challenge1/franklinvp_test.py‎

Lines changed: 56 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,13 @@
44

55

66
# Second Solution
7+
defconvert_to_path(perm):
8+
perm=list(perm)
9+
perm= [0]+perm+ [-1]
10+
path=list()
11+
foriinrange(1,len(perm)):
12+
path.append((perm[i-1],perm[i]))
13+
returnpath
714

815
defsolution(time,time_limit):
916
rows=len(time)
@@ -25,17 +32,11 @@ def solution(time, time_limit):
2532
path=convert_to_path(perm)
2633
forstart,endinpath:
2734
total_time+=time[start][end]
35+
2836
iftotal_time<=time_limit:
2937
returnsorted(list(i-1foriinperm))
30-
returnNone
3138

32-
defconvert_to_path(perm):
33-
perm=list(perm)
34-
perm= [0]+perm+ [-1]
35-
path=list()
36-
foriinrange(1,len(perm)):
37-
path.append((perm[i-1],perm[i]))
38-
returnpath
39+
returnNone
3940

4041

4142
### First Solution
@@ -120,15 +121,15 @@ def BellmanFord(times, time_limit):
120121
classTestSolution(unittest.TestCase):
121122

122123
cases= [
123-
#[
124-
# [[0, 1, 1, 1, 1],
125-
# [1, 0, 1, 1, 1],
126-
# [1, 1, 0, 1, 1],
127-
# [1, 1, 1, 0, 1],
128-
# [1, 1, 1, 1, 0]],
129-
# [3],
130-
# [[0,1]]
131-
#],
124+
[
125+
[[0,1,1,1,1],
126+
[1,0,1,1,1],
127+
[1,1,0,1,1],
128+
[1,1,1,0,1],
129+
[1,1,1,1,0]],
130+
[3],
131+
[[0,1]]
132+
],
132133

133134
[
134135
[[0,2,2,2,-1],
@@ -140,17 +141,17 @@ class TestSolution(unittest.TestCase):
140141
[[1,2]]
141142
],
142143

143-
#[
144-
# [
145-
# [0, 1, 1, 1, 1, 1, 1],
146-
# [1, 0, 1, 1, 1, 1, 1],
147-
# [1, 1, 0, 1, 1, 1, 1],
148-
# [1, 1, 1, 0, 1, 1, 1],
149-
# [1, 1, 1, 1, 0, 1, 1],
150-
# [1, 1, 1, 1, 1, 0, 1],
151-
# [1, 1, 1, 1, 1, 1, 0]
152-
# ],[3],[[0,1]]
153-
#],
144+
[
145+
[
146+
[0,1,1,1,1,1,1],
147+
[1,0,1,1,1,1,1],
148+
[1,1,0,1,1,1,1],
149+
[1,1,1,0,1,1,1],
150+
[1,1,1,1,0,1,1],
151+
[1,1,1,1,1,0,1],
152+
[1,1,1,1,1,1,0]
153+
],[3],[[0,1]]
154+
],
154155

155156
# [
156157
# [
@@ -160,27 +161,40 @@ class TestSolution(unittest.TestCase):
160161
# [9, 3, 2, 0, 0],
161162
# [9, 0, 0, 2, 0],
162163
# [-1, 3, 2, 2, 0]
163-
# ],
164-
# [1],
165-
# [[0,1,2]]
166-
# ]
164+
# ], [9], [[0,1,2,3]]
165+
# ],
166+
167+
# Matrix with Negative cycle
168+
[
169+
[
170+
[0,3,1,8,1],
171+
[2,0,9,4,2],
172+
[-5,1,0,3,-2],
173+
[3,2,1,0,1],
174+
[1,3,2,0,0]
175+
], [10], [[0,1,2]]
176+
]
167177
]
168178

169179

170180
deftest_solution(self):
171-
a="GeEK"
172-
# no length entered so default length
173-
# taken as 4(the length of string GeEK)
174-
p=itertools.permutations(a)
181+
### Permutations example
182+
# a = "GeEK"
183+
# # no length entered so default length
184+
# # taken as 4(the length of string GeEK)
185+
# p = itertools.permutations(a)
186+
# # Print the obtained permutations
187+
# for j in list(p):
188+
# print(j)
189+
# print([x for x in range(5)])
175190

176-
# Print the obtained permutations
177-
forjinlist(p):
178-
print(j)
179-
191+
### Reversed example
192+
# alph = ["a", "b", "c", "d"]
193+
# ralph = reversed(alph)
194+
# for x in ralph:
195+
# print(x)
180196

181-
print([xforxinrange(5)])
182197
forxinself.cases[:]:
183-
# print(int())
184198
got=solution(x[0],x[1][0] )
185199
self.assertEqual(got,x[2][0] )
186200

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp