about summary refs log tree commit diff
path: root/scratch/facebook/graph-coloring.py
diff options
context:
space:
mode:
authorWilliam Carroll <wpcarro@gmail.com>2020-11-12T14·37+0000
committerWilliam Carroll <wpcarro@gmail.com>2020-11-12T14·37+0000
commitaa66d9b83d5793bdbb7fe28368e0642f7c3dceac (patch)
treea0e6ad240fe1cdfd2fcdba7266931beea9fbe0d6 /scratch/facebook/graph-coloring.py
parentd2d772e43e0d4fb1bfaaa58d7de0c9e2cc274a25 (diff)
Add coding exercises for Facebook interviews
Add attempts at solving coding problems to Briefcase.
Diffstat (limited to 'scratch/facebook/graph-coloring.py')
-rw-r--r--scratch/facebook/graph-coloring.py60
1 files changed, 60 insertions, 0 deletions
diff --git a/scratch/facebook/graph-coloring.py b/scratch/facebook/graph-coloring.py
new file mode 100644
index 000000000000..17588166c871
--- /dev/null
+++ b/scratch/facebook/graph-coloring.py
@@ -0,0 +1,60 @@
+from collections import deque
+
+class Palette(object):
+    def __init__(self, n):
+        self.i = 0
+        self.colors = list(range(n))
+
+    def get(self):
+        return self.colors[self.i]
+
+    def advance(self):
+        self.i += 1 % len(self.colors)
+
+class GraphNode(object):
+    def __init__(self, label):
+        self.label = label
+        self.neighbors = set()
+        self.color = None
+
+    def __repr__(self):
+        result = []
+        xs = deque()
+        xs.append(self)
+        seen = set()
+        while xs:
+            node = xs.popleft()
+            result.append('{} ({})'.format(node.label, str(node.color)))
+            seen.add(node.label)
+            for c in node.neighbors:
+                if c.label not in seen:
+                    xs.append(c)
+        return ', '.join(result)
+
+def color_graph(graph, d):
+    seen = set()
+    start = graph
+    xs = deque()
+    palette = Palette(d + 1)
+    xs.append((start, palette.get()))
+    while xs:
+        x, color = xs.popleft()
+        x.color = color
+        seen.add(x.label)
+        for c in x.neighbors:
+            if c.label not in seen:
+                palette.advance()
+                xs.append((c, palette.get()))
+
+a = GraphNode('a')
+b = GraphNode('b')
+c = GraphNode('c')
+
+a.neighbors.add(b)
+b.neighbors.add(a)
+b.neighbors.add(c)
+c.neighbors.add(b)
+
+print(a)
+color_graph(a, 3)
+print(a)