Generates a permutation of 0, 1, 2, ..., n-1, which is useful for
sampling without replacement.
764772
public int[] permutate(int n) {
        int[] x = new int[n];
        for (int i = 0; i < n; i++) {
            x[i] = i;
        }

        permutate(x);

        return x;
    }
319000
function PermutationIterator() {
    function fact(n) {
        var result = 1;

        for (var i = 2; i <= n; i++) {
            result *= i;
        }

        return result;
    }

    var items = Array.prototype.slice.call(arguments, 0);

    this.items = (items.length == 1 && Array.isArray(items[0])) ? items[0] : items;
    this.max = (this.items.length > 0) ? fact(this.items.length) : 0;
    this.reset();
}
572414
def p(i, sample_size, weights):
        

        # Determine the initial pick values
        weight_i = weights[i]
        weights_sum = sum(weights)

        # Build a list of weights that don't contain the weight `i`. This list will
        # be used to build the possible picks before weight `i`.
        other_weights = list(weights)
        del other_weights[i]

        # Calculate the probability
        probability_of_i = 0
        for picks in range(0, sample_size):

            # Build the list of possible permutations for this pick in the sample
            permutations = list(itertools.permutations(other_weights, picks))

            # Calculate the probability for this permutation
            permutation_probabilities = []
            for permutation in permutations:

                # Calculate the probability for each pick in the permutation
                pick_probabilities = []
                pick_weight_sum = weights_sum

                for pick in permutation:
                    pick_probabilities.append(pick / pick_weight_sum)

                    # Each time we pick we update the sum of the weight the next
                    # pick is from.
                    pick_weight_sum -= pick

                # Add the probability of picking i as the last pick
                pick_probabilities += [weight_i / pick_weight_sum]

                # Multiply all the probabilities for the permutation together
                permutation_probability = reduce(
                    lambda x, y: x * y, pick_probabilities
                    )
                permutation_probabilities.append(permutation_probability)

            # Add together all the probabilities for all permutations together
            probability_of_i += sum(permutation_probabilities)

        return probability_of_i
294284
public static void permute( int[] perm , double []input , double[]output , int N ) {
        for (int k = 0; k < N; k++) {
            output[k] = input[perm[k]];
        }
    }
517042
public static void permutationInverse( int []original , int []inverse , int length ) {
        for (int i = 0; i < length; i++) {
            inverse[original[i]] = i;
        }
    }
1128275
public static <E> Collection<E> sampleWithoutReplacement(Collection<E> c, int n, Random r) {
    if (n < 0)
      throw new IllegalArgumentException("n < 0: " + n);
    if (n > c.size())
      throw new IllegalArgumentException("n > size of collection: " + n + ", " + c.size());
    List<E> copy = new ArrayList<E>(c.size());
    copy.addAll(c);
    Collection<E> result = new ArrayList<E>(n);
    for (int k = 0; k < n; k++) {
      double d = r.nextDouble();
      int x = (int) (d * copy.size());
      result.add(copy.remove(x));
    }
    return result;
  }
1220426
public static void sampleWithoutReplacement(int[] array, int numArgClasses, Random rand) {
    int[] temp = new int[numArgClasses];
    for (int i = 0; i < temp.length; i++) {
      temp[i] = i;
    }
    shuffle(temp, rand);
    System.arraycopy(temp, 0, array, 0, array.length);
  }
1084387
def random_combination(iterable, r):
    ""
    pool = tuple(iterable)
    n = len(pool)
    indices = sorted(random.sample(xrange(n), r))
    return tuple(pool[i] for i in indices)
712950
private List<Integer> getPermutation(Matrix4d transformation) {
		double rmsdThresholdSq = Math
				.pow(this.parameters.getRmsdThreshold(), 2);

		List<Point3d> centers = subunits.getOriginalCenters();
		List<Integer> seqClusterId = subunits.getClusterIds();

		List<Integer> permutations = new ArrayList<Integer>(centers.size());
		double[] dSqs = new double[centers.size()];
		boolean[] used = new boolean[centers.size()];
		Arrays.fill(used, false);

		for (int i = 0; i < centers.size(); i++) {
			Point3d tCenter = new Point3d(centers.get(i));
			transformation.transform(tCenter);
			int permutation = -1;
			double minDistSq = Double.MAX_VALUE;
			for (int j = 0; j < centers.size(); j++) {
				if (seqClusterId.get(i) == seqClusterId.get(j)) {
					if (!used[j]) {
						double dSq = tCenter.distanceSquared(centers.get(j));
						if (dSq < minDistSq && dSq <= rmsdThresholdSq) {
							minDistSq = dSq;
							permutation = j;
							dSqs[j] = dSq;
						}
					}
				}
			}
			// can't map to itself
			if (permutations.size() == permutation) {
				permutation = -1;
			}

			if (permutation != -1) {
				used[permutation] = true;
			}

			permutations.add(permutation);
		}

		return permutations;
	}
544373
def exactly_n(l, n=1):
    '''
    
    '''
    i = iter(l)
    return all(any(i) for j in range(n)) and not any(i)
1085212
public static <T> Collection<List<T>> permutations(Collection<T> elements) {
        Collection<List<T>> result = new ArrayList<>();
        if (elements.isEmpty()) {
            result.add(new LinkedList<>());
            return result;
        }

        List<T> rest = new LinkedList<>(elements);
        T head = rest.remove(0);
        for (List<T> permutations : permutations(rest)) {
            List<List<T>> subLists = new ArrayList<>();
            for (int i = 0; i <= permutations.size(); i++) {
                List<T> subList = new ArrayList<>();
                subList.addAll(permutations);
                subList.add(i, head);
                subLists.add(subList);
            }
            result.addAll(subLists);
        }
        return result;
    }
356899
def _get_casing_permutations(cls, input_string):
        
        if not input_string:
            yield ""
        else:
            first = input_string[:1]
            for sub_casing in cls._get_casing_permutations(input_string[1:]):
                yield first.lower() + sub_casing
                yield first.upper() + sub_casing
139138
def _conv_general_permutations(self, dimension_numbers):
    """"""
    lhs_spec, rhs_spec, out_spec = dimension_numbers
    lhs_char, rhs_char, out_char = ('N', 'C'), ('O', 'I'), ('N', 'C')
    charpairs = (lhs_char, rhs_char, out_char)
    for i, (a, b) in enumerate(charpairs):
      if not (dimension_numbers[i].count(a) == 1 and
              dimension_numbers[i].count(b) == 1):
        msg = ('convolution dimension_numbers[{}] must contain the characters '
               '"{}" and "{}" exatly once, got {}.')
        raise TypeError(msg.format(i, a, b, dimension_numbers[i]))
      if len(dimension_numbers[i]) != len(set(dimension_numbers[i])):
        msg = ('convolution dimension_numbers[{}] cannot have duplicate '
               'characters, got {}.')
        raise TypeError(msg.format(i, dimension_numbers[i]))
    if not (set(lhs_spec) - set(lhs_char) == set(rhs_spec) - set(rhs_char) ==
            set(out_spec) - set(out_char)):
      msg = ('convolution dimension_numbers elements must each have the same '
             'set of spatial characters, got {}.')
      raise TypeError(msg.format(dimension_numbers))

    def getperm(spec, charpair):
      spatial = (i for i, c in enumerate(spec) if c not in charpair)
      if spec is not rhs_spec:
        spatial = sorted(spatial, key=lambda i: rhs_spec.index(spec[i]))
      return (spec.index(charpair[0]), spec.index(charpair[1])) + tuple(spatial)

    lhs_perm, rhs_perm, out_perm = map(getperm, dimension_numbers, charpairs)
    return lhs_perm, rhs_perm, out_perm
116480
private final void print_30_permut()
    {
        // declare and initialize
        final int[] permutation = new int[n];
        for ( int i = 0; i < n; i++ )
        {
            permutation[i] = i;
            System.out.print((1 + i));
        }
        System.out.println();
        
        final int[] perm_remain = new int[n];
        for ( int i = 1; i <= n; i++ )
            perm_remain[i -1] = i;
        
        int numPermutationsPrinted = 1;
        for ( int pos_right = 2; pos_right <= n; pos_right++ )
        {
            int pos_left = pos_right -1;
            do
            {
                // rotate down perm[0..prev] by one
                next_perm(permutation, pos_left);
                
                if (--perm_remain[pos_left] > 0)
                {
                    if (numPermutationsPrinted++ < 30)
                    {
                        for (int i = 0; i < n; ++i)
                            System.out.print((1 + permutation[i]));
                        System.out.println();
                    }
                    else
                        return;
                    
                    for ( ; pos_left != 1; --pos_left)
                        perm_remain[pos_left -1] = pos_left;
                }
                else
                    ++pos_left;
            } while (pos_left < pos_right);
        }
    }
147125
def binom(n, k):
    
    # http://blog.plover.com/math/choose.html
    if k > n:
        return 0
    if k == 0:
        return 1
    result = 1
    for denom in range(1, k + 1):
        result *= n
        result /= denom
        n -= 1
    return result
588185
def _shuffled(seq):
    """"""
    fixed_random = random.Random()
    if six.PY2:  # pragma: no cover (py2)
        fixed_random.seed(FIXED_RANDOM_SEED)
    else:  # pragma: no cover (py3)
        fixed_random.seed(FIXED_RANDOM_SEED, version=1)

    seq = list(seq)
    random.shuffle(seq, random=fixed_random.random)
    return seq
1374531
public static int[] sampleWithoutReplacement(int m, int n) {
        // This implements a modified form of the genshuf() function from
        // Programming Pearls pg. 129.
        
        // TODO: Design a faster method that only generates min(m, n-m) integers.
        
        int[] array = getIndexArray(n);
        for (int i=0; i<m; i++) {
            int j = Prng.nextInt(n - i) + i;
            // Swap array[i] and array[j]
            int tmp = array[i];
            array[i] = array[j];
            array[j] = tmp;
        }
        return Arrays.copyOf(array, m);
    }