Skip to content

Instantly share code, notes, and snippets.

@Fawers
Created November 25, 2023 17:52
Show Gist options
  • Save Fawers/8cb96ae369e8df8c12942e15df5ebbda to your computer and use it in GitHub Desktop.
Save Fawers/8cb96ae369e8df8c12942e15df5ebbda to your computer and use it in GitHub Desktop.
n buckets problem solutions

There are N buckets arranged in a row. Each bucket either is empty or contains a ball. The buckets are specified as a string buckets consisting of characters "." (empty bucket) and " B " (bucket with aball). For example, for buckets = "B. BB. B. . B" the row of buckets appears as follows: In one move you can take the ball out of any bucket and place it in another (empty) bucket. Your goal is to arrange the balls to create an alternating sequence of full and empty buckets. In other words, the distance between two consecutive balls should be equal to 2. Note that the sequence may start at any bucket. For example, in the figure below, the balls are placed correctly: On the other hand, in both of the figures below, the balls are placed incorrectly: What is the minimum number of moves required to create a correct sequence of balls in buckets


Replits:

from functools import reduce
def solution(buckets):
left = buckets.find('B')
right = buckets.rfind('B')
balls_substr = buckets[left:right+1]
balls = balls_substr.count('B')
if len(buckets) // 2 <= balls:
return -1
arranged_balls = '.'.join('B' * balls)
return reduce(
lambda moves, pair: (moves + 1) if pair == ('.', 'B') else moves,
zip(buckets[left:], arranged_balls),
0)
print(solution('BB...B.B..BB.BBB.B....'))
@Fawers
Copy link
Author

Fawers commented Nov 25, 2023

To whomever is reading this:

I've received this task in an interview, and had to leave it with a score of 0 because 50 minutes under pressure is not enough for me to think through the problem and come up with a good solution. Frustrated, I decided to visualize the final output and come up with a solution while not time-restrained to share it publicly on the internet. This is a protest against shitty coding tasks during short interview time. If you're an interviewee, please use this solution for your own benefit. Adapt however you'd like. Use the system against itself.

Disclaimer: I don't have access to the task's original tests, and thus cannot confirm it works exactly as it should. If that's the case, you should be only a few tweaks away from the correct answer. Shove it up in theirs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment