-
Notifications
You must be signed in to change notification settings - Fork 0
/
solver.py
953 lines (848 loc) · 32.1 KB
/
solver.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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
# (C) 2015 Jean Nassar
# Released under the GNU General Public License, version 3
"""
Solver for *Keep Talking and Nobody Explodes*.
Based on *Bomb Defusal Manual*, v1r2, verification code 241. [#]_
References
----------
.. [#] Bomb Defusal Manual, Version 1, Verification Code 241, Revision 2.
http://www.bombmanual.com/manual/1/html/index.html
"""
class SerialNumber(object):
"""
Class for the serial number.
Parameters
----------
number : str
The serial number of the bomb.
Attributes
----------
number : str
The serial number of the bomb.
digits : list of int
The sequence of digits in the serial number.
"""
def __init__(self, number):
self.number = number
self.digits = [int(i) for i in self.number if i.isdigit()]
def has_vowel(self):
"""
Check if the serial number contains any vowels.
Returns
-------
bool
True if the serial number contains a vowel.
"""
return any(letter in self.number.lower() for letter in "aeiou")
def last_odd(self):
"""
Check if the last digit in the serial number is odd.
Returns
-------
bool
True if the last digit is odd.
"""
return self.digits[-1] % 2
def last_even(self):
"""
Check if the last digit in the serial number is even.
Returns
-------
bool
True if the last digit is odd.
"""
return not self.last_odd()
class Bomb(object):
"""
The bomb to be defused.
Parameters
----------
serial_number : SerialNumber
The serial number of the bomb.
n_batteries : int
The number of batteries on the bomb.
has_parallel : bool
Whether the bomb has a parallel port.
frk : bool
Whether the bomb has a FRK indicator.
car : bool
Whether the bomb has a CAR indicator.
Attributes
----------
serial_number : string
The serial number of the bomb.
n_batteries : int
The number of batteries on the bomb.
has_parallel : bool
Whether the bomb has a parallel port.
frk : bool
Whether the bomb has a FRK indicator.
car : bool
Whether the bomb has a CAR indicator.
n_strikes : int
The number of strikes the team has committed.
"""
def __init__(self, serial_number, n_batteries, has_parallel=False, frk=False, car=False):
self.serial_number = SerialNumber(serial_number)
self.n_batteries = n_batteries
self.has_parallel = has_parallel
self.frk = frk
self.car = car
self.n_strikes = 0
def strike(self):
"""
Register a strike.
"""
self.n_strikes += 1
def wires(self, wires):
"""
Solve a *Wires* module.
Parameters
----------
wires : str
A string containing the code for the wire colours.
**Colours :**
- black : k
- blue : b
- red : r
- white : w
- yellow : y
Therefore, a module containing three modules with white, blue, and
black, would be input as "wbk".
Returns
-------
to_cut : str
The wire to cut, ordinal from left to right starting with one.
"""
wires = wires.lower()
ordinal = ["FIRST", "SECOND", "THIRD", "FOURTH", "FIFTH", "SIXTH"]
if len(wires) == 3:
if "r" not in wires:
to_cut = "SECOND"
elif wires[-1] == "w":
to_cut = "THIRD"
elif wires.count("b") > 1:
to_cut = ordinal[2 - wires[::-1].index("b")]
else:
to_cut = "THIRD"
elif len(wires) == 4:
if wires.count("r") > 1 and self.serial_number.last_odd():
to_cut = ordinal[2 - wires[::-1].index("r")]
elif ((wires[-1] == "y"and wires.count("r") == 0)
or wires.count("b") == 1):
to_cut = "FIRST"
elif wires.count("y") > 1:
to_cut = "FOURTH"
else:
to_cut = "SECOND"
elif len(wires) == 5:
if wires[-1] == "k" and self.serial_number.last_odd():
to_cut = "FOURTH"
elif wires.count("r") == 1 and wires.count("y") > 1:
to_cut = "FIRST"
elif wires.count("k") == 0:
to_cut = "SECOND"
else:
to_cut = "FIRST"
else:
if wires.count("y") == 0 and self.serial_number.last_odd():
to_cut = "THIRD"
elif wires.count("y") == 0 and wires.count("w") > 1:
to_cut = "FOURTH"
elif wires.count("r") == 0:
to_cut = "SIXTH"
else:
to_cut = "FOURTH"
return to_cut
def button(self, text, colour):
"""
Solve a *Button* module.
Parameters
----------
text : str
The text on the button.
colour : char
The colour of the button.
**Colours :**
- blue : b
- red : r
- white : w
- yellow : y
- none : n
Returns
-------
str
Instruction for the diffuser
"""
def release():
"""
Determine the number at which to release the button.
Returns
-------
The number at which to release the button.
"""
colour = input("Strip colour: ").lower()
if colour == "b":
number = "FOUR"
elif colour == "y":
number = "FIVE"
else:
number = "ONE"
return number
text = text.lower()
if text == "abort" and colour == "b":
to_hold = True
elif self.n_batteries > 1 and text == "detonate":
to_hold = False
elif colour == "w" and self.car:
to_hold = True
elif self.n_batteries > 2 and self.frk:
to_hold = False
elif colour == "y":
to_hold = True
elif text == "hold" and colour == "r":
to_hold = False
else:
to_hold = True
if to_hold:
return "HOLD until the timer contains a {n}".format(n=release())
else:
return "PRESS and immediately RELEASE"
def keypad(self, *keys):
"""
Solve a *Keypads* module.
Parameters
----------
keys : str
The names of the buttons. The order does not matter. Use as many as
needed.
The symbols below have the recommended name in the beginning. Feel
free to change them.
- Ϙ: Q, neuter, uncrossed-female, hand-mirror, O-with-a-♥♥♥♥
- Ѧ: at, three-legged A, A-with-a-♥♥♥♥, little Yus
- ƛ: lambda, crossed lambda, half-life
- Ѭ: an, cthulhu, big Yus
- Ϟ: koppa, zigzag
- ϗ: H, cursive H/N with tail
- Ͽ: moon, crescent, backwards C, backwards C with-a-dot
- Ӭ: eh, epsilon, epsilon umlaut, euro
- Ҩ: loop, rollercoaster, cursive I, loop-dee-loop
- ☆: star, open star, empty star
- ¿: que, question, upside-down question mark, Spanish question mark
- ©: copy, copyright
- Ѽ: butt, ot, xbox, cyrillic omega
- Ж: zhe, X with an I
- Ԇ: hoe, komi dzje, incomplete R, trailing off 3
- ƀ: B, keyblade, crossed b, barred b, BT smashed
- б: 6, six, smashed 6, upside-down g, hooktop b
- ¶: para, paragraph, line-break, backwards P
- ټ: derp-face, smiley, Isolated Teh
- Ͼ: C, C with a dot
- Ѯ: ksi, dragon, alien 3, 3-with-antenna
- ★: black, blackstar, filled star, full star
- Ψ: psi, trident
- ҂: neq (pronounced neck), inequality, unequal
- æ: ae, "A E", ash
- Й: i, N, N with antenna, N with tail
- Ω: Omega
So the columns, from left to right, are:
- [q, at, lambda, koppa, an, h, moon]
- [eh, q, moon, loop, star, h, que]
- [copy, butt, loop, zhe, hoe, lambda, star]
- [6, para, b, an, zhe, que, smile]
- [psi, smile, b, c, para, ksi, black]
- [6, eh, neq, ae, psi, i, omega]
Returns
-------
str
The order in which the buttons are to be pressed.
"""
columns = [
['q', 'at', 'lambda', 'koppa', 'an', 'h', 'moon'],
['eh', 'q', 'moon', 'loop', 'star', 'h', 'que'],
['copy', 'ot', 'loop', 'zhe', 'hoe', 'lambda', 'star'],
['6', 'para', 'b', 'an', 'zhe', 'que', 'smile'],
['psi', 'smile', 'b', 'c', 'para', 'ksi', 'black'],
['6', 'eh', 'neq', 'ae', 'psi', 'i', 'omega']
]
working_column = None
keyset = set(keys)
output = []
for column in columns:
if len(set(column).intersection(keyset)) == 4:
working_column = column
break
for key in working_column:
if key in keys:
output.append(key)
return output
def simon(self):
"""
Solve a *Simon Says* module.
Run the solver, then input a colour every time. The solver will
generate the appropriate response. If a strike is incurred during the
loop, simply halt the operation of the program, run `strike`, and try
again.
**Colours :**
- blue : b
- green : g
- red : r
- yellow : y
"""
map_with_vowel = {
0: {"r": "b",
"b": "r",
"g": "y",
"y": "g"},
1: {"r": "y",
"b": "g",
"g": "b",
"y": "r"},
2: {"r": "g",
"b": "r",
"g": "y",
"y": "b"}
}
map_with_no_vowel = {
0: {"r": "b",
"b": "y",
"g": "g",
"y": "r"},
1: {"r": "r",
"b": "b",
"g": "y",
"y": "g"},
2: {"r": "y",
"b": "g",
"g": "b",
"y": "r"}
}
colour_map = map_with_vowel if self.serial_number.has_vowel() else map_with_no_vowel
while True:
try:
colour = input("Colour: ")
print(colour_map[n_strikes][colour])
except KeyboardInterrupt:
break
def whos(self):
"""
Solve a *Who's on First* problem.
Run the solver. On each iteration, input the letters on the display.
The diffuser shall then relay the label of the appropriate button.
The expert would then speak a list of the words, one at a time,
until a match is found. The diffuser presses the matching button.
"""
responses = {
"READY": ("YES, OKAY, WHAT, MIDDLE, LEFT, PRESS, RIGHT, BLANK, "
"READY, NO, FIRST, UHHH, NOTHING, WAIT"),
"FIRST": ("LEFT, OKAY, YES, MIDDLE, NO, RIGHT, NOTHING, UHHH, "
"WAIT, READY, BLANK, WHAT, PRESS, FIRST"),
"NO": ("BLANK, UHHH, WAIT, FIRST, WHAT, READY, RIGHT, YES, "
"NOTHING, LEFT, PRESS, OKAY, NO, MIDDLE"),
"BLANK": ("WAIT, RIGHT, OKAY, MIDDLE, BLANK, PRESS, READY, "
"NOTHING, NO, WHAT, LEFT, UHHH, YES, FIRST"),
"NOTHING": ("UHHH, RIGHT, OKAY, MIDDLE, YES, BLANK, NO, PRESS, "
"LEFT, WHAT, WAIT, FIRST, NOTHING, READY"),
"YES": ("OKAY, RIGHT, UHHH, MIDDLE, FIRST, WHAT, PRESS, READY, "
"NOTHING, YES, LEFT, BLANK, NO, WAIT"),
"WHAT": ("UHHH, WHAT, LEFT, NOTHING, READY, BLANK, MIDDLE, NO, "
"OKAY, FIRST, WAIT, YES, PRESS, RIGHT"),
"UHHH": ("READY, NOTHING, LEFT, WHAT, OKAY, YES, RIGHT, NO, PRESS, "
"BLANK, UHHH, MIDDLE, WAIT, FIRST"),
"LEFT": ("RIGHT, LEFT, FIRST, NO, MIDDLE, YES, BLANK, WHAT, UHHH, "
"WAIT, PRESS, READY, OKAY, NOTHING"),
"RIGHT": ("YES, NOTHING, READY, PRESS, NO, WAIT, WHAT, RIGHT, "
"MIDDLE, LEFT, UHHH, BLANK, OKAY, FIRST"),
"MIDDLE": ("BLANK, READY, OKAY, WHAT, NOTHING, PRESS, NO, WAIT, "
"LEFT, MIDDLE, RIGHT, FIRST, UHHH, YES"),
"OKAY": ("MIDDLE, NO, FIRST, YES, UHHH, NOTHING, WAIT, OKAY, LEFT, "
"READY, BLANK, PRESS, WHAT, RIGHT"),
"WAIT": ("UHHH, NO, BLANK, OKAY, YES, LEFT, FIRST, PRESS, WHAT, "
"WAIT, NOTHING, READY, RIGHT, MIDDLE"),
"PRESS": ("RIGHT, MIDDLE, YES, READY, PRESS, OKAY, NOTHING, UHHH, "
"BLANK, LEFT, FIRST, WHAT, NO, WAIT"),
"YOU": ("SURE, YOU ARE, YOUR, YOU'RE, NEXT, UH HUH, UR, HOLD, "
"WHAT?, YOU, UH UH, LIKE, DONE, U"),
"YOU ARE": ("YOUR, NEXT, LIKE, UH HUH, WHAT?, DONE, UH UH, HOLD, "
"YOU, U, YOU'RE, SURE, UR, YOU ARE"),
"YOUR": ("UH UH, YOU ARE, UH HUH, YOUR, NEXT, UR, SURE, U, YOU'RE, "
"YOU, WHAT?, HOLD, LIKE, DONE"),
"YOU'RE": ("YOU, YOU'RE, UR, NEXT, UH UH, YOU ARE, U, YOUR, WHAT?, "
"UH HUH, SURE, DONE, LIKE, HOLD"),
"UR": ("DONE, U, UR, UH HUH, WHAT?, SURE, YOUR, HOLD, YOU'RE, "
"LIKE, NEXT, UH UH, YOU ARE, YOU"),
"U": ("UH HUH, SURE, NEXT, WHAT?, YOU'RE, UR, UH UH, DONE, U, YOU, "
"LIKE, HOLD, YOU ARE, YOUR"),
"UH HUH": ("UH HUH, YOUR, YOU ARE, YOU, DONE, HOLD, UH UH, NEXT, "
"SURE, LIKE, YOU'RE, UR, U, WHAT?"),
"UH UH": ("UR, U, YOU ARE, YOU'RE, NEXT, UH UH, DONE, YOU, UH HUH, "
"LIKE, YOUR, SURE, HOLD, WHAT?"),
"WHAT?": ("YOU, HOLD, YOU'RE, YOUR, U, DONE, UH UH, LIKE, YOU ARE, "
"UH HUH, UR, NEXT, WHAT?, SURE"),
"DONE": ("SURE, UH HUH, NEXT, WHAT?, YOUR, UR, YOU'RE, HOLD, LIKE, "
"YOU, U, YOU ARE, UH UH, DONE"),
"NEXT": ("WHAT?, UH HUH, UH UH, YOUR, HOLD, SURE, NEXT, LIKE, "
"DONE, YOU ARE, UR, YOU'RE, U, YOU"),
"HOLD": ("YOU ARE, U, DONE, UH UH, YOU, UR, SURE, WHAT?, YOU'RE, "
"NEXT, HOLD, UH HUH, YOUR, LIKE"),
"SURE": ("YOU ARE, DONE, LIKE, YOU'RE, YOU, HOLD, UH HUH, UR, "
"SURE, U, WHAT?, NEXT, YOUR, UH UH"),
"LIKE": ("YOU'RE, NEXT, U, UR, HOLD, DONE, UH UH, WHAT?, UH HUH, "
"YOU, LIKE, SURE, YOU ARE, YOUR")
}
while True:
try:
display = input("Display: ")
if display == "ur":
print("TOP LEFT")
elif display in ("first", "okay", "c"):
print("TOP RIGHT")
elif display in ("yes", "nothing", "led", "they are"):
print("MIDDLE LEFT")
elif display in ("blank", "read", "red", "you", "your", "you're", "their"):
print("MIDDLE RIGHT")
elif display in ("", "reed", "leed", "they're"):
print("BOTTOM LEFT")
else:
print("BOTTOM RIGHT")
label = input("Button label: ")
print(responses[label.upper()])
except KeyboardInterrupt:
break
def memory(self):
"""
Solve a *Memory* module.
Run the solver. The diffuser should relay the number on the screen.
The expert instructs with regards to the button to be pressed.
Note that this can be either the label, or the position of the button.
Once a button is pressed, the diffuser confirms its number and
position, which is then input into the solver.
"""
class Solution(object):
"""
A solution container.
"""
def __init__(self):
self.position = None
self.label = None
def solve_stage(stage, display):
"""
Solve a given stage.
Appends a solution to the `pressed` array.
Parameters
----------
stage : int
The stage to be solved.
display : str
The text on the module display.
"""
soln = Solution()
if stage == 1:
if display in ("1", "2"):
soln.position = "SECOND"
elif display == "3":
soln.position = "THIRD"
else:
soln.position = "FOURTH"
elif stage == 2:
if display in ("2", "4"):
soln.position = pressed[0].position
elif display == "1":
soln.label = "FOUR"
else:
soln.position = "FIRST"
elif stage == 3:
if display == "1":
soln.label = pressed[1].label
elif display == "2":
soln.label = pressed[0].label
elif display == "3":
soln.position = "THIRD"
elif display == "4":
soln.value = "FOUR"
elif stage == 4:
if display in ("3", "4"):
soln.position = pressed[1].position
elif display == "1":
soln.position = pressed[0].position
else:
soln.position = "FIRST"
else:
if display == "1":
soln.label = pressed[0].label
elif display == "2":
soln.label = pressed[1].label
elif display == "3":
soln.label = pressed[3].label
else:
soln.label = pressed[2].label
if soln.position is None:
print(soln.label)
soln.position = input("Button position: ")
else:
print(soln.position)
soln.label = input("Button label: ")
pressed.append(soln)
pressed = []
for i in range(1, 6):
try:
print("Stage {}:".format(i))
display = input("Display: ")
solve_stage(i, display)
print("-" * 20)
except KeyboardInterrupt:
break
def morse(self):
"""
Solve a *Morse Code* problem.
If the diffuser knows morse code, they can relay the letter directly.
Otherwise, they may speak the dits (dots) and dahs (dashes) out loud.
The expert would enter them one at a time and the solver will
interpret them.
Returns
-------
str
The frequency to be selected.
"""
decrypt = {
".-" : "A", "-...": "B", "-.-.": "C",
"-.." : "D", "." : "E", "..-.": "F",
"--." : "G", "....": "H", ".." : "I",
".---": "J", "-.-" : "K", ".-..": "L",
"--" : "M", "-." : "N", "---" : "O",
".--.": "P", "--.-": "Q", ".-." : "R",
"..." : "S", "-" : "T", "..-" : "U",
"...-": "V", ".--" : "W", "-..-": "X",
"-.--": "Y", "--..": "Z",
}
frequency = {
"shell": "3.505",
"halls": "3.515",
"slick": "3.522",
"trick": "3.532",
"boxes": "3.535",
"leaks": "3.542",
"strobe": "3.545",
"bistro": "3.552",
"flick": "3.555",
"bombs": "3.565",
"break": "3.572",
"brick": "3.575",
"steak": "3.582",
"sting": "3.592",
"vector": "3.595",
"beats": "3.600"
}
active = set(frequency.keys())
for i in range(6):
try:
char = input("Letter or morse: ")
if char.isalnum():
letter = char
else:
letter = decrypt[char].lower()
working_active = active.copy()
for word in active:
if word[i] != letter:
working_active.remove(word)
active = working_active
if len(active) == 1:
return frequency[active.pop()], " Mhz"
except KeyboardInterrupt:
break
def complicated(self):
"""
Solve a *Complicated Wires* module.
Run the solver. For each wire, input whether the LED is on ("1") or off
("0"), the wire colour, and whether a star is ("1") or is not ("0")
drawn. The colours are shown below.
**Colours :**
- blue : b
- red : r
- striped : s
- none : n
For each wire, wait until the expert declares whether or not to
cut the wire before proceeding.
"""
def decide(letter):
"""Print out whether or not to cut a wire."""
if letter == "C":
to_cut = True
elif letter == "D":
to_cut = False
elif letter == "S":
to_cut = True if self.serial_number.last_even() else False
elif letter == "P":
to_cut = True if self.has_parallel else False
else:
to_cut = True if self.n_batteries >= 2 else False
if to_cut:
print("CUT")
else:
print("DO NOT CUT")
instructions = ["C", "C", "S", "D", # 0000 to 0011
"S", "C", "S", "P", # 0100 to 0111
"D", "B", "P", "P", # 1000 to 1011
"B", "B", "S", "D"] # 1100 to 1111
idx = 1
while True:
try:
led, colour, star = input("Wire {}. led, colour, star: ".format(idx))
if colour == "r":
blue = "0"
red = "1"
elif colour == "b":
blue = "1"
red = "0"
elif colour == "s":
blue = "1"
red = "1"
else:
blue = "0"
red = "0"
case = int("".join((led, red, blue, star)), 2)
letter = instructions[case]
decide(letter)
idx += 1
except KeyboardInterrupt:
break
def sequences(self):
"""
Solve a *Wire Sequences* module.
Run the solver. For each step, enter the colour of the wire, and its
connection. The solver prints the decision for each wire.
**Colours :**
- blue : b
- black : k
- red : r
"""
counts = {"r": 0, "b": 0, "k": 0}
cuts = {
"r": ["c", "b", "a", "ac", "b", "ac", "abc", "ab", "b"],
"b": ["b", "ac", "b", "a", "b", "bc", "c", "ac", "a"],
"k": ["abc", "ac", "b", "ac", "b", "bc", "ab", "c", "c"]
}
while True
try:
colour, connection = input("Colour and connection: ")
print("CUT" if connection in cuts[colour][counts[colour]]
else "DO NOT CUT")
counts[colour] += 1
except KeyboardInterrupt:
break
def maze(self, indicator, start, target):
"""
Solve a *Maze* module.
The coordinates take the form of a tuple. The origin is at the top-left
corner of the maze. The first element denotes the x-direction, with
positive being to the right. The second element denotes the
y-direction, with positive being downwards. Note that all tuples start
at zero.
Parameters
----------
indicator : (int, int)
The location of one indicator.
start : (int, int)
The starting location of the user.
target : (int, int)
The location of the target.
Returns
-------
instructions : list of str
A list of directions to take one at a time.
"""
if indicator in [(0, 1), (5, 2)]:
maze = [
["rd", "lr", "ld", "rd", "lr", "l"],
["ud", "rd", "ul", "ur", "lr", "ld"],
["ud", "ur", "ld", "rd", "lr", "uld"],
["ud", "r", "ulr", "lu", "r", "uld"],
["urd", "lr", "ld", "rd", "l", "ud"],
["ur", "l", "ur", "ul", "r", "ul"]
]
elif indicator in [(4, 1), (1, 3)]:
maze = [
["r", "lrd", "l", "rd", "lrd", "l"],
["rd", "ul", "rd", "ul", "ur", "ld"],
["ud", "rd", "ul", "rd", "lr", "uld"],
["urd", "ul", "rd", "ul", "d", "ud"],
["ud", "d", "ud", "rd", "ul", "ud"],
["u", "ur", "ul", "ur", "lr", "lu"]
]
elif indicator in [(3, 3), (5, 3)]:
maze = [
["dr", "lr", "ld", "d", "dr", "dl"],
["u", "d", "ud", "ur", "lu", "ud"],
["dr", "uld", "ud", "rd", "ld", "ud"],
["ud", "ud", "ud", "ud", "ud", "ud"],
["ud", "ur", "ul", "ud", "ud", "ud"],
["ur", "lr", "lr", "ul", "ur", "ul"]
]
elif indicator in [(0, 0), (0, 3)]:
maze = [
["rd", "ld", "r", "lr", "lr", "ld"],
["ud", "ud", "dr", "lr", "lr", "uld"],
["ud", "ur", "lu", "rd", "l", "ud"],
["ud", "r", "lr", "lru", "lr", "lud"],
["udr", "lr", "lr", "lr", "ld", "ud"],
["ur", "lr", "l", "r", "ul", "u"]
]
elif indicator in [(4, 2), (3, 5)]:
maze = [
["r", "lr", "lr", "lr", "lrd", "ld"],
["rd", "lr", "lr", "lrd", "lu", "u"],
["udr", "ld", "r", "ul", "rd", "ld"],
["ud", "ur", "lr", "ld", "u", "ud"],
["ud", "rd", "lr", "ulr", "l", "ud"],
["u", "ur", "lr", "lr", "lr", "lu"]
]
elif indicator in [(4, 0), (2, 4)]:
maze = [
["d", "dr", "ld", "r", "ldr", "ld"],
["ud", "ud", "ud", "rd", "ul", "ud"],
["udr", "ul", "u", "ud", "rd", "ul"],
["ur", "ld", "dr", "udl", "ud", "d"],
["rd", "ul", "u", "ud", "ur", "uld"],
["ur", "lr", "lr", "ul", "r", "ul"]
]
elif indicator in [(1, 0), (1, 5)]:
maze = [
["dr", "lr", "lr", "ld", "dr", "ld"],
["ud", "rd", "l", "ur", "lu", "ud"],
["ur", "ul", "rd", "l", "rd", "ul"],
["dr", "ld", "udr", "lr", "ul", "d"],
["ud", "u", "ur", "lr", "ld", "ud"],
["ur", "lr", "lr", "lr", "ulr", "ul"]
]
elif indicator in [(3, 0), (2, 3)]:
maze = [
["d", "dr", "lr", "ld", "dr", "ld"],
["udr", "ulr", "l", "ur", "ul", "ud"],
["ud", "dr", "lr", "lr", "ld", "ud"],
["ud", "ur", "ld", "r", "ulr", "ul"],
["ud", "d", "ur", "lr", "lr", "l"],
["ur", "ulr", "lr", "lr", "lr", "l"]
]
elif indicator in [(1, 2), (0, 4)]:
maze = [
["d", "dr", "lr", "lr", "ldr", "ld"],
["ud", "ud", "rd", "l", "ud", "ud"],
["udr", "ulr", "ul", "rd", "ul", "ud"],
["ud", "d", "dr", "ul", "r", "uld"],
["ud", "ud", "ud", "dr", "dl", "u"],
["ur", "ul", "ur", "ul", "ur", "l"]
]
else:
return "Error: Maze not found!"
visited = []
branches = []
moves = []
i, j = start
while (i, j) != target:
print(i, j)
visited.append((i, j))
moves.append((i, j))
val = maze[j][i]
n_possible = len(val)
if "u" in val and (i, j-1) in visited:
n_possible -= 1
if "d" in val and (i, j+1) in visited:
n_possible -= 1
if "l" in val and (i-1, j) in visited:
n_possible -= 1
if "r" in val and (i+1, j) in visited:
n_possible -= 1
if n_possible > 1:
branches.append((i, j))
if "u" in val and (i, j-1) not in visited:
j -= 1
elif "d" in val and (i, j+1) not in visited:
j += 1
elif "l" in val and (i-1, j) not in visited:
i -= 1
elif "r" in val and (i+1, j) not in visited:
i += 1
else:
i, j = branches.pop()
moves = moves[:moves.index((i, j))]
moves.append(target)
instructions = []
for current, move in zip(moves, moves[1:]):
if move[1] < current[1]:
instructions.append("up")
elif move[1] > current[1]:
instructions.append("down")
elif move[0] < current[0]:
instructions.append("left")
else:
instructions.append("right")
return instructions
def passwords(self, initial):
"""
Solve a *Passwords* module.
Run the solver. For each position, input all the possible letters
which can be entered. The expert would obtain a shrinking list
of possible passwords.
Parameters
----------
initial : str
The initial sequence of letters.
"""
all_passwords = (
"about", "after", "again", "below", "could",
"every", "first", "found", "great", "house",
"large", "learn", "never", "other", "place",
"plant", "point", "right", "small", "sound",
"spell", "still", "study", "their", "there",
"these", "thing", "think", "three", "water",
"where", "which", "world", "would", "write"
)
active = set()
for pos, letter in enumerate(initial):
for word in all_passwords:
if word[pos] == letter:
active.add(word)
print("Active words: {}".format(active))
for i in range(5):
possibilities = input("All possible in position {}: ".format(i))
working_active = active.copy()
for word in active:
if word[i] not in possibilities:
working_active.remove(word)
active = working_active
print("Active words: {}".format(active))
def venting(self):
"""Solve a *Venting Gas* module."""
return "YES"
def capacitor(self):
"""Solve a *Capacitor Discharge* module."""
return "HOLD DOWN LEVER"
def knob(self, top_row):
"""
Solve a *Knob* module.
In some cases, the status of the bottom LEDs may need to be provided.
Parameters
----------
top_row : str
The status of the LEDs on the top row, from left to right. "1"
denotes a lit LED, and "0" denotes one which is off.
Returns
-------
str
The direction relative to "UP" in which to move the knob.
"""
if top_row == "101010":
bottom_row = input("Bottom row: ")
if bottom_row == "011011":
return "UP"
else:
return "DOWN"
else:
if top_row == "001011":
return "UP"
elif top_row == "011001":
return "DOWN"
elif top_row == "000010":
return "LEFT"
else:
return "RIGHT"