import random


def selected_cojunctions(cojunctions, max_refs=300,
                            seq='ATC', rname='chr1', sense='+'):
    """ Selects the max_ref cojunctions with the fewest junctions.

        Ties are broken at random.

        cojunctions: list of junction combinations
        max_refs: maximum number of cojunctions to return
        seq, rname, and sense are used for random seed if necessary

        Return value: truncated cojunctions list
    """
    if len(cojunctions) <= max_refs:
        return cojunctions
    cojunctions.sort(key=len)
    if len(cojunctions[max_refs]) == len(cojunctions[max_refs - 1]):
        # Shuffle cojunctions, then resort
        random.seed(seq + rname + sense)
        random.shuffle(cojunctions)
        cojunctions.sort(key=len)
    return cojunctions[:max_refs]