Java List Permutate permVisit(int[] value, int n, int k, List res)

Here you can find the source of permVisit(int[] value, int n, int k, List res)

Description

Helper method for generating the integer sequence permutations.

License

Apache License

Declaration

private static void permVisit(int[] value, int n, int k, List<int[]> res) 

Method Source Code

//package com.java2s;
/* Copyright 2012-2015 SAP SE
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.// w  w w.  ja v a  2  s  .  c  o m
 */

import java.util.List;

public class Main {
    private static int permLevel = -1;

    /**
     * Helper method for generating the integer sequence permutations. Should
     * not be used on its own!
     *
     */
    private static void permVisit(int[] value, int n, int k, List<int[]> res) {
        permLevel = permLevel + 1;
        value[k] = permLevel;

        if (permLevel == n) {
            res.add(copySubarray(value, 0, value.length));
        } else {
            for (int i = 0; i < n; i++) {
                if (value[i] == 0)
                    permVisit(value, n, i, res);
            }
        }
        permLevel = permLevel - 1;
        value[k] = 0;

    }

    /**
     * Copies a subarray of a given array and returns it.
     *
     * @param src
     *            The source array that should be used.
     * @param start
     *            The start index.
     * @param end
     *            The end index.
     * @return A subarray of the source array, including the value at the start
     *         index and excluding the value at the end index.
     */
    private static int[] copySubarray(int[] src, int start, int end) {

        int[] res = new int[end - start];
        int resPos = 0;

        for (int i = start; i < end; i++) {
            res[resPos] = src[i];
            resPos++;
        }

        return res;
    }
}

Related

  1. permute(T[] arr, List p)
  2. permutedGroups(List> elementLists)
  3. permuteList(List list, int[] permutations)
  4. permuteList(List in, int seed)
  5. permuteList(List list, Integer[] permutation)