Skip to content
GitLab
Projects
Groups
Snippets
Help
Loading...
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Sign in
Toggle navigation
Open sidebar
public
cyberbits
Commits
c99f6ff5
Commit
c99f6ff5
authored
Jun 26, 2018
by
Mike Borowczak
Browse files
complete puzzle
parent
69d1b430
Changes
1
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
100 additions
and
0 deletions
+100
-0
session-1-puzzled/puzzle-complete.py
session-1-puzzled/puzzle-complete.py
+100
-0
No files found.
session-1-puzzled/puzzle-complete.py
0 → 100644
View file @
c99f6ff5
from
microbit
import
*
size
=
3
grid
=
[[
4
,
1
,
3
],
[
7
,
2
,
6
],
[
0
,
5
,
8
]]
solvedGrid
=
[[
1
,
2
,
3
],
[
4
,
5
,
6
],
[
7
,
8
,
0
]]
def
copy
(
grid
):
return
[[
y
for
y
in
x
]
for
x
in
grid
]
def
isSolved
(
grid
):
return
grid
==
solvedGrid
def
showGrid
(
grid
):
for
x
in
range
(
1
,
size
+
1
):
for
y
in
range
(
1
,
size
+
1
):
display
.
set_pixel
(
y
,
x
,
grid
[
x
-
1
][
y
-
1
])
def
lightUp
():
display
.
set_pixel
(
0
,
0
,
9
)
display
.
set_pixel
(
0
,
4
,
9
)
display
.
set_pixel
(
4
,
0
,
9
)
display
.
set_pixel
(
4
,
4
,
9
)
def
getMoves
(
grid
):
# find the zero
for
x
in
range
(
size
):
for
y
in
range
(
size
):
if
grid
[
x
][
y
]
==
0
:
zerox
=
x
zeroy
=
y
# where can we move?
xswaps
=
[((
zerox
,
zeroy
),
(
x
,
zeroy
))
for
x
in
[
zerox
-
1
,
zerox
+
1
]
if
x
>=
0
and
x
<
size
]
yswaps
=
[((
zerox
,
zeroy
),
(
zerox
,
y
))
for
y
in
[
zeroy
-
1
,
zeroy
+
1
]
if
y
>=
0
and
y
<
size
]
return
xswaps
+
yswaps
def
swap
(
grid
,
move
):
pos0
,
pos1
=
move
x0
,
y0
=
pos0
x1
,
y1
=
pos1
tmp
=
grid
[
x0
][
y0
]
grid
[
x0
][
y0
]
=
grid
[
x1
][
y1
]
grid
[
x1
][
y1
]
=
tmp
# distance of current grid to target grid, defined as number of pieces that are
# in the wrong position
def
distance
(
grid
,
move
):
swap
(
grid
,
move
)
diff
=
0
for
x
in
range
(
size
):
for
y
in
range
(
size
):
diff
+=
solvedGrid
[
x
][
y
]
!=
grid
[
x
][
y
]
swap
(
grid
,
(
move
[
1
],
move
[
0
]))
return
diff
visited
=
[]
toVisit
=
[
grid
]
def
bfs
():
while
len
(
toVisit
)
>
0
:
grid
=
toVisit
.
pop
()
visited
.
append
(
copy
(
grid
))
showGrid
(
grid
)
sleep
(
500
)
if
isSolved
(
grid
):
return
grid
moves
=
getMoves
(
grid
)
# sort according to score
moves
.
sort
(
key
=
lambda
e
:
distance
(
grid
,
e
),
reverse
=
True
)
for
move
in
moves
:
swap
(
grid
,
move
)
if
grid
not
in
visited
:
toVisit
.
append
(
copy
(
grid
))
swap
(
grid
,
(
move
[
1
],
move
[
0
]))
showGrid
(
grid
)
grid
=
bfs
()
lightUp
()
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment