import random
import math


def scheduleGamesForPlayer(nPlayers, pIndex):
    """ Given the total number of players (nPlayers), and the index of the current
    player (pIndex), returns a list of games scheduled against the player such
    that pIndex will play against each player (including herself) at least
    once, at most twice, in the least number of games possible, with no game
    containing two opponents of the same type.  These games occur in
    randomized order (and opponent pairs are also randomized).
    Games are returned as a 2D list of player indices,
        result = scheduleGamesForPlayer(...)
    result[0] is the first game to be played
    result[0][0] is always pIndex
    result[0][1] and result[0][2] are the opponents
    Example usage:
    > scheduleGamesForPlayer(10, 1)
    produces 5 games as follows:
    > [[1, 0, 4], [1, 5, 9], [1, 3, 7], [1, 8, 2], [1, 1, 6]]
    """
    playerList = [i for i in range(nPlayers)]
    random.shuffle(playerList)
    nBasicGames = int(math.floor(nPlayers / 2))
    schedule = []
    for i in range(nBasicGames):
        schedule.append([pIndex, playerList[i*2], playerList[i*2+1]])
    # If number of players is odd, we schedule one extra game with the
    # remaining opponent and a randomly selected player.  The additional
    # opponent cannot be the same as this last outstanding opponent.
    if nPlayers % 2 == 1:
        r = random.randint(0, nPlayers-2)
        if r == playerList[-1]:
            r += 1
        schedule.append([pIndex, playerList[-1], r])
    return schedule