Created
November 6, 2013 11:26
-
-
Save yannick1974/7334581 to your computer and use it in GitHub Desktop.
A simple solution to "Twitter interview problem" (http://qandwhat.apps.runkite.com/i-failed-a-twitter-interview/, https://gist.github.com/mkozakov/59af0fd5bddbed1a0399) using numpy.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
from matplotlib import pyplot as plt | |
def waterfill(walls): | |
land = np.zeros((len(walls), max(walls)), dtype=int) | |
# Put the walls | |
for index, value in enumerate(walls): | |
land[index, 0:value] = 2 | |
# Drop water | |
land[land == 0] = 1 | |
# Remove flowed-out water | |
for height in range(0, max(walls))[::-1]: | |
left_max = land[:, height].argmax() | |
right_max = len(walls) - land[:, height][::-1].argmax() | |
land[:left_max, height] = 0 | |
land[right_max:, height] = 0 | |
return len(land[land == 1]) | |
def waterfill_with_plots(walls): | |
land = np.zeros((len(walls), max(walls)), dtype=int) | |
fig = plt.figure() | |
# Put the walls | |
for index, value in enumerate(walls): | |
land[index, 0:value] = 2 | |
dry_land = np.copy(land) | |
dry_fig = fig.add_subplot(1, 2, 1) | |
dry_fig.imshow(np.transpose(dry_land), | |
origin="lower", | |
interpolation="nearest") | |
# Drop water | |
land[land == 0] = 1 | |
# Remove flowed-out water | |
for height in range(0, max(walls))[::-1]: | |
left_max = land[:, height].argmax() | |
right_max = len(walls) - land[:, height][::-1].argmax() | |
land[:left_max, height] = 0 | |
land[right_max:, height] = 0 | |
wet_fig = fig.add_subplot(1, 2, 2) | |
wet_fig.imshow(np.transpose(land), | |
origin="lower", | |
interpolation="nearest") | |
fig.suptitle("{} filled blocks".format(len(land[land == 1]))) | |
fig.show() |
Well, the graph looks good to me...
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The graph is wrong for [7, 1, 1, 1, 7, 1, 1, 1, 1, 7], but the solution is wright 42