create one kind of permutation - all other permutations can be created from this particular permutation through transformations
485529
function (M) { //starting at bottom right, moving horizontally
    var jump = false,
      tl = n * n,
      br = 1,
      inc = 1,
      row, col, val, i, j;
    M[0][0] = tl;
    M[n - 1][n - 1] = br;

    for (i = 1; i < n; i++) {
      //generate top/bottom row
      if (jump) {
        tl -= 4 * inc;
        br += 4 * inc;
        inc++;
      } else {
        tl--;
        br++;
      }

      M[0][i] = tl;
      M[n - 1][n - 1 - i] = br;
      jump = !jump;
    }

    var dec = true;
    for (i = 1; i < n; i++) {
      //iterate diagonally from top row
      row = 0;
      col = i;
      val = M[row][col];

      for (j = 1; j < i + 1; j++) {
        if (dec) {
          val -= 1;
        } else {
          val += 1;
        }
        row++;
        col--;
        M[row][col] = val;
      }
      dec = !dec;
    }

    if (n % 2 === 0) {
      dec = true;
    } else {
      dec = false;
    }
    for (i = 1; i < n - 1; i++) {
      //iterate diagonally from bottom row
      row = n - 1;
      col = i;
      val = M[row][col];

      for (j = 1; j < n - i; j++) {
        if (dec) {
          val--;
        } else {
          val++;
        }
        row--;
        col++;
        M[row][col] = val;
      }
      dec = !dec;
    }
    return M;
  }
1104472
def transform(pattern):
    
    result = []
    groups = [[pattern]]
    while groups:
        children = groups.pop(0)
        parents = [Required, Optional, OptionsShortcut, Either, OneOrMore]
        if any(t in map(type, children) for t in parents):
            child = [c for c in children if type(c) in parents][0]
            children.remove(child)
            if type(child) is Either:
                for c in child.children:
                    groups.append([c] + children)
            elif type(child) is OneOrMore:
                groups.append(child.children * 2 + children)
            else:
                groups.append(child.children + children)
        else:
            result.append(children)
    return Either(*[Required(*e) for e in result])
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
287239
public static <T> void permutations(List<List<T>> result, List<T> args, int index) {
        if (index == args.size() - 2) {
            List<T> temp1 = new ArrayList<>(args.size());
            temp1.addAll(args);
            Collections.swap(temp1, index, index + 1);
            result.add(temp1);
            List<T> temp2 = new ArrayList<>(args.size());
            temp2.addAll(args);
            result.add(temp2);
            return;
        }
        permutations(result, args, index + 1);
        for (int i = index; i < args.size() - 1; i++) {
            List<T> temp = new ArrayList<>(args.size());
            temp.addAll(args);
            Collections.swap(temp, index, i + 1);
            permutations(result, temp, index + 1);
        }
    }
614882
public List<PermutationSolution<Integer>> doCrossover(double probability, List<PermutationSolution<Integer>> parents) {
    List<PermutationSolution<Integer>> offspring = new ArrayList<>(2);

    offspring.add((PermutationSolution<Integer>) parents.get(0).copy()) ;
    offspring.add((PermutationSolution<Integer>) parents.get(1).copy()) ;

    int permutationLength = parents.get(0).getNumberOfVariables() ;

    if (crossoverRandomGenerator.getRandomValue() < probability) {
      int cuttingPoint1;
      int cuttingPoint2;

      // STEP 1: Get two cutting points
      cuttingPoint1 = cuttingPointRandomGenerator.getRandomValue(0, permutationLength - 1);
      cuttingPoint2 = cuttingPointRandomGenerator.getRandomValue(0, permutationLength - 1);
      while (cuttingPoint2 == cuttingPoint1)
        cuttingPoint2 = cuttingPointRandomGenerator.getRandomValue(0, permutationLength - 1);

      if (cuttingPoint1 > cuttingPoint2) {
        int swap;
        swap = cuttingPoint1;
        cuttingPoint1 = cuttingPoint2;
        cuttingPoint2 = swap;
      }

      // STEP 2: Get the subchains to interchange
      int replacement1[] = new int[permutationLength];
      int replacement2[] = new int[permutationLength];
      for (int i = 0; i < permutationLength; i++)
        replacement1[i] = replacement2[i] = -1;

      // STEP 3: Interchange
      for (int i = cuttingPoint1; i <= cuttingPoint2; i++) {
        offspring.get(0).setVariableValue(i, parents.get(1).getVariableValue(i));
        offspring.get(1).setVariableValue(i, parents.get(0).getVariableValue(i));

        replacement1[parents.get(1).getVariableValue(i)] = parents.get(0).getVariableValue(i) ;
        replacement2[parents.get(0).getVariableValue(i)] = parents.get(1).getVariableValue(i) ;
      }

      // STEP 4: Repair offspring
      for (int i = 0; i < permutationLength; i++) {
        if ((i >= cuttingPoint1) && (i <= cuttingPoint2))
          continue;

        int n1 = parents.get(0).getVariableValue(i);
        int m1 = replacement1[n1];

        int n2 = parents.get(1).getVariableValue(i);
        int m2 = replacement2[n2];

        while (m1 != -1) {
          n1 = m1;
          m1 = replacement1[m1];
        }

        while (m2 != -1) {
          n2 = m2;
          m2 = replacement2[m2];
        }

        offspring.get(0).setVariableValue(i, n1);
        offspring.get(1).setVariableValue(i, n2);
      }
    }

    return offspring;
  }
898894
private void refine(PermutationGroup group, Partition coarser) {
        int vertexCount = getVertexCount();

        Partition finer = equitableRefiner.refine(coarser);

        int firstNonDiscreteCell = finer.getIndexOfFirstNonDiscreteCell();
        if (firstNonDiscreteCell == -1) {
            firstNonDiscreteCell = vertexCount;
        }

        Permutation pi1 = new Permutation(firstNonDiscreteCell);

        Result result = Result.BETTER;
        if (bestExist) {
            pi1 = finer.setAsPermutation(firstNonDiscreteCell);
            result = compareRowwise(pi1);
        }

        // partition is discrete
        if (finer.size() == vertexCount) {
            if (!bestExist) {
                best = finer.toPermutation();
                first = finer.toPermutation();
                bestExist = true;
            } else {
                if (result == Result.BETTER) {
                    best = new Permutation(pi1);
                } else if (result == Result.EQUAL) {
                    group.enter(pi1.multiply(best.invert()));
                }
            }
        } else {
            if (result != Result.WORSE) {
                Set<Integer> blockCopy = finer.copyBlock(firstNonDiscreteCell);
                for (int vertexInBlock = 0; vertexInBlock < vertexCount; vertexInBlock++) {
                    if (blockCopy.contains(vertexInBlock)) {
                        Partition nextPartition = finer.splitBefore(firstNonDiscreteCell, vertexInBlock);

                        this.refine(group, nextPartition);

                        int[] permF = new int[vertexCount];
                        int[] invF = new int[vertexCount];
                        for (int i = 0; i < vertexCount; i++) {
                            permF[i] = i;
                            invF[i] = i;
                        }

                        for (int j = 0; j <= firstNonDiscreteCell; j++) {
                            int x = nextPartition.getFirstInCell(j);
                            int i = invF[x];
                            int h = permF[j];
                            permF[j] = x;
                            permF[i] = h;
                            invF[h] = i;
                            invF[x] = j;
                        }
                        Permutation pPermF = new Permutation(permF);
                        group.changeBase(pPermF);
                        for (int j = 0; j < vertexCount; j++) {
                            Permutation g = group.get(firstNonDiscreteCell, j);
                            if (g != null) {
                                blockCopy.remove(g.get(vertexInBlock));
                            }
                        }
                    }
                }
            }
        }
    }
851133
def combinations(self):
        
        keys = self._vars.keys()
        for result in product(*self._vars.values()):
            possible_solution = {}
            for i, v in enumerate(result):
                possible_solution[keys[i]] = v
            yield possible_solution
242219
def p_NewOrClone(p):
    '''
    
    '''
    if len(p) > 3:
        p[0] = NewOrClone(p[1], p[2], p[4], None)
    else:
        p[0] = NewOrClone(p[1], None, None, p[2])
621599
private <IN1, IN2, OUT> Collection<Integer> transformTwoInputTransform(TwoInputTransformation<IN1, IN2, OUT> transform) {

		Collection<Integer> inputIds1 = transform(transform.getInput1());
		Collection<Integer> inputIds2 = transform(transform.getInput2());

		// the recursive call might have already transformed this
		if (alreadyTransformed.containsKey(transform)) {
			return alreadyTransformed.get(transform);
		}

		List<Integer> allInputIds = new ArrayList<>();
		allInputIds.addAll(inputIds1);
		allInputIds.addAll(inputIds2);

		String slotSharingGroup = determineSlotSharingGroup(transform.getSlotSharingGroup(), allInputIds);

		streamGraph.addCoOperator(
				transform.getId(),
				slotSharingGroup,
				transform.getCoLocationGroupKey(),
				transform.getOperator(),
				transform.getInputType1(),
				transform.getInputType2(),
				transform.getOutputType(),
				transform.getName());

		if (transform.getStateKeySelector1() != null || transform.getStateKeySelector2() != null) {
			TypeSerializer<?> keySerializer = transform.getStateKeyType().createSerializer(env.getConfig());
			streamGraph.setTwoInputStateKey(transform.getId(), transform.getStateKeySelector1(), transform.getStateKeySelector2(), keySerializer);
		}

		streamGraph.setParallelism(transform.getId(), transform.getParallelism());
		streamGraph.setMaxParallelism(transform.getId(), transform.getMaxParallelism());

		for (Integer inputId: inputIds1) {
			streamGraph.addEdge(inputId,
					transform.getId(),
					1
			);
		}

		for (Integer inputId: inputIds2) {
			streamGraph.addEdge(inputId,
					transform.getId(),
					2
			);
		}

		return Collections.singleton(transform.getId());
	}
1255783
public void permutate(int[] x) {
        for (int i = 0; i < x.length; i++) {
            int j = i + nextInt(x.length - i);
            Math.swap(x, i, j);
        }
    }
231068
public static DMatrixSparseCSC permutationMatrix(int[] p, boolean inverse, int N, DMatrixSparseCSC P) {

        if( P == null )
            P = new DMatrixSparseCSC(N,N,N);
        else
            P.reshape(N,N,N);
        P.indicesSorted = true;
        P.nz_length = N;

        // each column should have one element inside of it
        if( !inverse ) {
            for (int i = 0; i < N; i++) {
                P.col_idx[i + 1] = i + 1;
                P.nz_rows[p[i]] = i;
                P.nz_values[i] = 1;
            }
        } else {
            for (int i = 0; i < N; i++) {
                P.col_idx[i + 1] = i + 1;
                P.nz_rows[i] = p[i];
                P.nz_values[i] = 1;
            }
        }

        return P;
    }
1196767
public static <X, Y, Z> Triple<X, Y, Z> makeTriple(X x, Y y, Z z) {
    return new Triple<X, Y, Z>(x, y, z);
  }
388870
def __permutate(self, table, block):
		""""""
		return list(map(lambda x: block[x], table))
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]];
        }
    }
80282
function createCombinations(a, b) {
  var combinations = [''];
  var newCombinations;
  for (var i = 0, len = a.length; i < len; i += 1) {
    newCombinations = [];
    combinations.forEach(function (combination) {
      newCombinations.push(combination + a[i]);
      // Don't repeat work.
      if (a[i] !== b[i]) {
        newCombinations.push(combination + b[i]);
      }
    });
    combinations = newCombinations;
  }
  return combinations;
}
789326
public Integer[] nextPermutation() {
                if (permLeft.equals(permTotal)) {
                        permLeft = permLeft.subtract(BigInteger.ONE);
                        return position;
                }

                // Find largest index j with a[j] < a[j+1]
                int j = position.length - 2;
                while (position[j] > position[j + 1]) {
                        j--;
                }

                // Find index k such that a[k] is smallest integer
                // greater than a[j] to the right of a[j]
                int k = position.length - 1;
                while (position[j] > position[k]) {
                        k--;
                }

                // Interchange a[j] and a[k]
                int temp;
                temp = position[k];
                position[k] = position[j];
                position[j] = temp;

                // Put tail end of permutation after j-th position in increasing order
                int r = position.length - 1;
                int s = j + 1;
                while (r > s) {
                        temp = position[s];
                        position[s] = position[r];
                        position[r] = temp;
                        r--;
                        s++;
                }

                permLeft = permLeft.subtract(BigInteger.ONE);
                return position;
        }
567224
def get_dimension_permutations(entities, dimensions):
    """"""
    new_dimensions = defaultdict(int)
    for item in dimensions:
        new = entities[item['base']].dimensions
        if new:
            for new_item in new:
                new_dimensions[new_item['base']] += new_item['power'] * \
                                                 item['power']
        else:
            new_dimensions[item['base']] += item['power']

    final = [[{'base': i[0], 'power': i[1]} for i in new_dimensions.items()]]
    final.append(dimensions)
    final = [sorted(i, key=lambda x: x['base']) for i in final]

    candidates = []
    for item in final:
        if item not in candidates:
            candidates.append(item)

    return candidates