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

时间:2018-02-19 14:16:36

标签: java

如果我有[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);
            }
        }
    }

2 个答案:

答案 0 :(得分:0)

正如我上面所说,尝试将数组转换为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 

答案 1 :(得分:-1)

我在网上发现了一些内容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 */

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