Helper method for generating the integer sequence permutations. - Java java.lang

Java examples for java.lang:Math Number

Description

Helper method for generating the integer sequence permutations.

Demo Code

/* 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./*from   w  w  w .j a v  a  2  s .  c o m*/
 */
//package com.java2s;

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 Tutorials