import random


def _PickRandomBuilder(builders):
  """Randomly select one builder to do a full build for.

  This selects one of the builders and uses the relative age of the newest build
  (in revisions) for each cache as its weight for random selection, favoring the
  caches that are older.
  """
  for b in builders:
    b['newest_build'] = max(
        b['cache_stats'].full_build_commit_positions.values() or [0])
  # Do `or 1000` to avoid zero weight choices when the cache is new. Any
  # number greater than zero would work.
  newest_build = max([b['newest_build'] for b in builders]) or 1000
  for b in builders:
    b['cache_age'] = newest_build - b['newest_build']

  # Weighted random selection
  weight_sum = sum(b['cache_age'] for b in builders)
  r = random.uniform(0, weight_sum)
  for b in builders:  # pragma: no branch
    if r <= b['cache_age']:
      return b
    r -= b['cache_age']