import random


def majority_vote(vectors, problem_embedding, random_state=42):
    """
    Unembeds raw D-Wave samples using the majority vote function.
    Unbiased majority vote in that if the chain is split 50-50, then random
    choice is used.

    Parameters
    ----------
    vectors : list
        Raw vectors from the D-Wave solver. The length is equal
        to the number of anneals. Each element in vectors is a list of
        length equal to the number of qubits on thee D-Wave device. For the
        case of a D-Wave 2000Q, the number of qubits  is 2048 (including active and inactive).
    problem_embedding : dict
        Logical embedding for the problem that D-Wave solved. Keys are
        variable names, and values are a list of physical qubits representing
        the logical state of the variable (key).

    Returns
    -------
    all_vectors_unembedded : list
        List of dictionaries. The number of dictionaries is equal to
        the length of thee input variable vectors. Each dictionary is
        has the same keys as problem_embedding, and the values
        are either 0 1 since this function handles QUBOS.

    """
    random.seed(random_state)

    all_vectors_unembedded = []
    for v in vectors:
        unembedded = {}
        for chain in problem_embedding:
            count_1 = 0
            count_0 = 0
            for qubit in problem_embedding[chain]:
                if v[qubit] == 0:
                    count_0 += 1
                if v[qubit] == 1:
                    count_1 += 1
            if count_0 == count_1:
                unembedded[chain] = random.choice([0, 1])
            if count_0 > count_1:
                unembedded[chain] = 0
            if count_1 > count_0:
                unembedded[chain] = 1
        all_vectors_unembedded.append(unembedded)
    return all_vectors_unembedded