简体   繁体   中英

How to get all sub arrays of specific length from array

If I have array like [1,2,3,4] and k = 3 then output should be [1,2,3][2,3,4][1,3,4] which is in sorted order.

I can do it when k = 2 but can't think of a way to do it more generic for any value of 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);
            }
        }
    }

As I said above try to convert array to ArrayList, sort it. Imagine that now you have an original paper with list of your integer values. You copy this paper, cross off one of the integer values in copy and put this paper into your folder (HashSet in the following code). Then copy original again and so on.

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();
    }
}

}

Result of the executing of the code will be:

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 

UPDATE: I read your question more attentively and decided to rewrite the code for meeting the main requirement: find all sorted subarrays with size k in the array with size n.

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();
    }
}
}

And result is:

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 

I found something on internet here https://www.geeksforgeeks.org/print-all-possible-combinations-of-r-elements-in-a-given-array-of-size-n/

The code use a permutation function :

// 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 */

Once you have all the permutation you just have to build an array with it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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