import torch


def multiple_index_select(t, index):
    """
    Permute columns of a given tensor for each row independently of the others
    :param t: tensor with at least 2 dimensions
    :param index: 2D LongTensor with size corresponding to the first two dims

    >>> a, b, c = list(range(0, 2)), list(range(2, 4)), list(range(4, 6))
    >>> t = torch.LongTensor([[a, b, c], [c, b, c]])
    >>> index = torch.LongTensor([[1, 2, 0], [0, 1, 1]])
    >>> multiple_index_select(t, index).tolist()
    [[[2, 3], [4, 5], [0, 1]], [[4, 5], [2, 3], [2, 3]]]
    """
    # check dimensions
    for dim, (tdim, indexdim) in enumerate(zip(t.size(), index.size())):
        if tdim != indexdim:
            raise ValueError("Mismatch {dim}, {tdim} != {indexdim}".format(
                dim=dim, tdim=tdim, indexdim=indexdim
            ))
    offset = (torch.arange(0, index.size(0)) * index.size(1)).long()
    if t.is_cuda:
        offset = offset.cuda()
    size = [-1] + list(t.size()[2:])
    return t.view(*size)[(index + offset[:, None]).view(-1)].view(*t.size())