Toilet Seat Algorithm

Yes, there is a basic O(1) algorithm.

I start with the assumption both people start “ticking” at t=0.
I believe the solution should generalize to different starting times, but it isn’t hard to extend from one “free end” of the timeline to two ends.

Assume n <= m.

Then our timeline looks like this (an ‘x’ marks a ‘move’, not a visit)

  0     m    2m    ..              t-t%m  t
  +-----+-----+-----+-----+-----+-----+--o
W x     x     x     x     x     x     x 
M x  x    x    x       x     x    x     x?

So, the woman goes floor(t/m) times, and between
each time the woman goes — in the half-open interval (a*m, a*m+m]
the man goes at least once, thus flipping the seat once. For
each time that she flips the seat in an interval, he also flips it once.
However, he possibly will go once more after
her last trip, depending on their relative timings,
which you can calculate based on t modulo their respective periods.

total_moves = floor(t/m) * 2 + (t%m < t%n ? 1 : 0)

Now for the case n > m.

The roles of the woman and man are reversed… the half-open interval [a*n, a*n+n) will always involve two moves. The remainder
of the line is [t-t%n, t), in which the man goes once at the beginning,
(which is +1 move, but we counted +2 for both people’s moves at t=0, which we should probably discard) and the woman goes if she has equal or less time left than he does

total_moves = floor(t/n) * 2 - 1 + (t%m >= t%n ? 1 : 0)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)