Skip to content

Instantly share code, notes, and snippets.

@qpwo
Created October 4, 2017 01:32
Show Gist options
  • Save qpwo/2e077b7cec1d47325032a19bdc1ce391 to your computer and use it in GitHub Desktop.
Save qpwo/2e077b7cec1d47325032a19bdc1ce391 to your computer and use it in GitHub Desktop.
Solution to problem A in tonight's contest, with explanation of hashmaps
# A 'map' also known as a 'dictionary' also known as a 'hashmap':
# https://en.wikipedia.org/wiki/Hash_table
# It maps 'keys' to 'values'. Keys and values can be anything: strings, tuples, integers, floats...
# Here, the keys are integers and the values are lists of integers.
d = {
1: [1,2,3,4,5,6,7,8,9,0],
2: [2,3,5,6,8,9,0],
3: [3,6,9],
4: [4,5,6,7,8,9,0],
5: [5,6,8,9,0],
6: [6,9],
7: [7,8,9,0],
8: [8,9,0],
9: [9],
0: [0],
}
# The word 'path' comes from graph theory.
# https://en.wikipedia.org/wiki/Path_(graph_theory)
# A dictionary is essentially the adjacency list of a graph.
# You could say vertices in the graph are digits and an edge from V to W means your hand can go to W after you press V.
# A path is a list of vertices that are connected by edges.
# You can enumerate all the paths in a graph by brute force.
numbers = set()
for i in d:
numbers.add(i)
for j in d[i]:
numbers.add(10*i+j)
for k in d[j]:
numbers.add(100*i+10*j+k)
# We get the closest number by finding the one in the set with the smallest absolute difference.
def findClosest(n):
return min(numbers, key=lambda n: abs(num-n))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment