简体   繁体   中英

How do i optimize below code so that it can accept any array size and give me the result

The below code displays the subarrays of the given array. But if i increase array size by one the below code fails to display all the subarrays, to make it successfully display all the arrays i need to add one more for loop. So how can i optmize code so that it display all the subarrays dynamically by not depending on the array size.

public class Subarrays {

    public static void main(String[] args)
    {
        int[] arr=new int[] {1,-2,4,-5,1};
        int count=0;
        for(int i=0; i<arr.length; i++) {
            System.out.println("["+arr[i]+"]");
            for(int j=0; j<arr.length-(i+1); j++) {
            }
        }
        for(int i=0; i<arr.length-1; i++) {
            System.out.println("["+arr[i]+","+arr[i+1]+"]");
        }

        for(int i=0; i<arr.length-2;i++)
        {
            System.out.println("["+arr[i]+","+arr[i+1]+","+arr[i+2]+"]");
        }

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

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



    }


}
public static void printAllSubArrays(int[] arr) {
    for (int len = 1; len <= arr.length; len++) {
        for (int from = 0; from + len <= arr.length; from++) {
            System.out.print('[');

            for (int i = from; i < from + len; i++) {
                if (i != from)
                    System.out.print(',');
                System.out.print(arr[i]);
            }

            System.out.println(']');
        }
    }
}

Demo:

printAllSubArrays(new int[] { 1, -2, 4, -5, 1 });

Output:

[1]
[-2]
[4]
[-5]
[1]
[1, -2]
[-2, 4]
[4, -5]
[-5, 1]
[1, -2, 4]
[-2, 4, -5]
[4, -5, 1]
[1, -2, 4, -5]
[-2, 4, -5, 1]
[1, -2, 4, -5, 1]

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