繁体   English   中英

如何从数组中获取特定长度的所有子数组

[英]How to get all sub arrays of specific length from array

如果我有像 [1,2,3,4] 和 k = 3 这样的数组,那么输出应该是按排序顺序的 [1,2,3][2,3,4][1,3,4] 。

我可以在 k = 2 时做到这一点,但想不出对任何 k 值更通用的方法。

    final int arr[] = new int[] { 1, 2, 3, 4 };
    final int max = 2;
    for (int i = 0; i < arr.length - 1; i++) {
        for (int j = i + 1; j < arr.length; j++) {
            for (int k = 0; k < max; k = k + 2) {
                System.out.println(i + "" + j);
            }
        }
    }

正如我上面所说,尝试将数组转换为 ArrayList,对其进行排序。 想象一下,现在您有一份原始论文,其中包含您的整数值列表。 你复制这张纸,划掉复制中的一个整数值,然后把这张纸放到你的文件夹中(下面代码中的HashSet)。 然后再次复制原件,依此类推。

package Subarrays;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;

public class Subarrays {

public static void main(String[] arg) {
    int arraySize = 0;
    int initElementNumber = 0;
    int initElementValue = 0;

    Scanner scanner = new Scanner(System.in);
    // Creates an array
    System.out.println("Type the size of the array: ");
    do {
        try {
            arraySize = scanner.nextInt();
        } catch (Exception e) {
            e.printStackTrace();
        }
    } while (arraySize == 0);

    System.out.println("Type the number of element, which you want to initialize yourself: ");
    do {
        try {
            initElementNumber = scanner.nextInt();
        } catch (Exception e) {
            e.printStackTrace();
        }
    } while (initElementNumber == 0);

    System.out.println("Type value of the element: ");
    do {
        try {
            initElementValue = scanner.nextInt();
        } catch (Exception e) {
            e.printStackTrace();
        }
    } while (initElementValue == 0);

    Integer arr[] = new Integer[arraySize];
    arr[initElementNumber] = initElementValue;

    for (int i = 0; i < arr.length; i++) {
        if (i != initElementNumber) {
            arr[i] = i;
        }
    }

    // Converts the array to arrayList
    ArrayList<Integer> list = new ArrayList<Integer>(Arrays.asList(arr));

    // Sorts the list
    Collections.sort(list);

    // Creates a clone of the list
    ArrayList<Integer> listTemp = (ArrayList<Integer>) list.clone();

    // Creates a set of the future lists
    Set<ArrayList<Integer>> set = new HashSet<ArrayList<Integer>>();

    // Iterates over the list and removes one element
    for (int i = 0; i < list.size(); i++) {
        listTemp.remove(i); // listTemp restructured here
        // Adding listItem to set
        set.add(listTemp);
        // Creates new clone of the list
        listTemp = (ArrayList<Integer>) list.clone();
    }

    // Writes content of the set to the console
    for (List<Integer> list2 : set) {
        System.out.print("List: ");
        for (Integer integer2 : list2) {
            System.out.print(" " + integer2 + " ");
        }
        System.out.println();
    }
}

}

代码的执行结果将是:

Type the size of the array: 
5
Type the number of element, which you want to initialize yourself: 
2
Type value of the element: 
8
List:  0  3  4  8 
List:  0  1  4  8 
List:  1  3  4  8 
List:  0  1  3  8 
List:  0  1  3  4 

更新:我更仔细地阅读了您的问题,并决定重写代码以满足主要要求:在大小为 n 的数组中找到大小为 k 的所有已排序子数组。

package Subarrays;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;

public class Subarrays2 {

private static int ARRAY_SIZE = 0;
private static int SIZE_OF_SUBARRAYS = 0;
private static Set<ArrayList<Integer>> set = new HashSet<ArrayList<Integer>>();

public static void main(String[] arg) {

    Scanner scanner = new Scanner(System.in);
    // Creates an array
    System.out.println("Type the size of the array: ");
    do {
        try {
            ARRAY_SIZE = scanner.nextInt();
        } catch (Exception e) {
            e.printStackTrace();
        }
    } while (ARRAY_SIZE == 0);

    System.out.println("Type the size of subarrays: ");
    do {
        try {
            SIZE_OF_SUBARRAYS = scanner.nextInt();
        } catch (Exception e) {
            e.printStackTrace();
        }
    } while (SIZE_OF_SUBARRAYS == 0);
    scanner.close();

    Integer arr[] = new Integer[ARRAY_SIZE];

    for (int i = 0; i < ARRAY_SIZE; i++) {
        arr[i] = i;
    }

    // Converts the array to arrayList
    ArrayList<Integer> list = new ArrayList<Integer>(Arrays.asList(arr));

    // Sorts the list
    Collections.sort(list);

    recursion(list); // This method work until find all of the sorted lists 
    // with size SIZE_OF_SUBARRAYS in array with size ARRAY_SIZE 

    // Writes content of the set to the console
    for (List<Integer> list2 : set) {
        System.out.print("List: ");
        for (Integer integer2 : list2) {
            System.out.print(" " + integer2 + " ");
        }
        System.out.println();
    }
}


private static void recursion(ArrayList<Integer> notSmallestCombination) {
    ArrayList<Integer> listTemp = (ArrayList<Integer>) notSmallestCombination.clone();
    for (int i = 0; i < notSmallestCombination.size(); i++) {
        listTemp.remove(i);
        if (listTemp.size() == SIZE_OF_SUBARRAYS) {
            for (int j = 0; j < notSmallestCombination.size(); j++) {
                ArrayList<Integer> list2Temp = (ArrayList<Integer>) notSmallestCombination.clone();
                list2Temp.remove(j);
                set.add(list2Temp);
            }
        } else {
            recursion(listTemp);
        }
        listTemp = (ArrayList<Integer>) notSmallestCombination.clone();
    }
}
}

结果是:

Type the size of the array: 
5
Type the size of subarrays: 
3
List:  0  3  4 
List:  0  2  3 
List:  0  1  2 
List:  1  3  4 
List:  1  2  3 
List:  0  2  4 
List:  0  1  3 
List:  2  3  4 
List:  1  2  4 
List:  0  1  4 

我在互联网上找到了一些东西https://www.geeksforgeeks.org/print-all-possible-combinations-of-r-elements-in-a-given-array-of-size-n/

代码使用置换函数:

// Java program to print all combination of size r in an array of size n
import java.io.*;

class Permutation {

    /* arr[]  ---> Input Array
    data[] ---> Temporary array to store current combination
    start & end ---> Staring and Ending indexes in arr[]
    index  ---> Current index in data[]
    r ---> Size of a combination to be printed */
    static void combinationUtil(int arr[], int data[], int start,
                                int end, int index, int r)
    {
        // Current combination is ready to be printed, print it
        if (index == r)
        {
            for (int j=0; j<r; j++)
                System.out.print(data[j]+" ");
            System.out.println("");
            return;
        }

        // replace index with all possible elements. The condition
        // "end-i+1 >= r-index" makes sure that including one element
        // at index will make a combination with remaining elements
        // at remaining positions
        for (int i=start; i<=end && end-i+1 >= r-index; i++)
        {
            data[index] = arr[i];
            combinationUtil(arr, data, i+1, end, index+1, r);
        }
    }

    // The main function that prints all combinations of size r
    // in arr[] of size n. This function mainly uses combinationUtil()
    static void printCombination(int arr[], int n, int r)
    {
        // A temporary array to store all combination one by one
        int data[]=new int[r];

        // Print all combination using temprary array 'data[]'
        combinationUtil(arr, data, 0, n-1, 0, r);
    }

    /*Driver function to check for above function*/
    public static void main (String[] args) {
        int arr[] = {1, 2, 3, 4, 5};
        int r = 3;
        int n = arr.length;
        printCombination(arr, n, r);
    }
}

/* This code is contributed by Devesh Agrawal */

一旦你有了所有的排列,你只需要用它构建一个数组

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM