简体   繁体   中英

How to find sub-arrays of an array in java

This is a program I have written to print all possible sub-arrays of given array, But there is some problem in the logic and it is printing wrong output.

Is there any algo to implement this ??

public class SubArray {
static int[][] subArrs;
static int count = 0;

public static void main(String[] args) {
    int[] arr = { 1, 2, 3 };
    int N = 8;

    subArrs = new int[N][];
    subArrs[0] = new int[10];

    for (int i = 0; i < arr.length; i++) {
        subArrs[i] = new int[1];
        subArrs[i][0] = arr[i];
    }

    count = arr.length;
    for (int i = 0; i < arr.length; i++) {
        sub(arr, i, i);
    }

    for (int i = 0; i < subArrs.length; i++) {
        System.out.print("[ ");
        for (int j = 0; j < subArrs[i].length; j++) {
            System.out.print("  " + subArrs[i][j]);
        }
        System.out.println(" ]");
    }
}

this is a method to calculate sub-array having more than 1 element.

static void sub(int arr[], int i, int index) {
    for (int j = i + 1; j < arr.length; j++) {

        while (index <= j) {
            subArrs[count] = new int[j + 1];
            subArrs[count][0] = arr[i];

            for (int k = 1; k < (j + 1); k++) {
                subArrs[count][k] = arr[k];
            }
            count++;
            index++;
        }
    }

}
}

Output I am getting

[   1 ]
[   2 ]
[   3 ]
[   1  2 ]
[   1  2 ]
[   1  2  3 ]
[   2  2  3 ]
[   2  2  3 ]

Desired Output

[   1 ]
[   2 ]
[   3 ]
[   1  2 ]
[   1  3 ]
[   2  3 ]
[   1  2  3 ]

Try this code:

for (int i = 0; i < yourArray.length; i++)
    {
        // j is the number of elements which should be printed
        for (int j = i; j < yourArray.length; j++)
        {
            // print the array from i to j
            for (int k = i; k <= j; k++)
            {
                System.out.print(yourArray[k]);
            }
            System.out.println();
        }
    }

public class AD { static final String[] abc = {"a", "b", "c", "d"};

public static void main(String[] args) {
    System.out.println(JSON.toJSON(sub(Arrays.asList(abc), 1, abc.length)));
}

public static List<Object[]> sub(List list, int minSize, int maxSize) {
    if (minSize <= 0) {
        minSize = 1;
    }

    if (minSize > maxSize) {
        maxSize = minSize;
    }

    if (maxSize > list.size()) {
        maxSize = list.size();
    }
    List<Object[]> ret = new ArrayList<>();
    for (int i = minSize; i <= maxSize; i++) {
        ret.addAll(combine(abc, i));
    }

    return ret;
}

public static List combine(Object[] a, int m) {
    int n = a.length;
    if (m > n) {
        return null;
    }

    List result = new ArrayList();

    int[] bs = new int[n];
    for (int i = 0; i < n; i++) {
        bs[i] = 0;
    }
    // 初始化
    for (int i = 0; i < m; i++) {
        bs[i] = 1;
    }
    boolean flag = true;
    boolean tempFlag = false;
    int pos = 0;
    int sum = 0;
    // 首先找到第一个10组合,然后变成01,同时将左边所有的1移动到数组的最左边
    do {
        sum = 0;
        pos = 0;
        tempFlag = true;
        result.add(print(bs, a, m));

        for (int i = 0; i < n - 1; i++) {
            if (bs[i] == 1 && bs[i + 1] == 0) {
                bs[i] = 0;
                bs[i + 1] = 1;
                pos = i;
                break;
            }
        }
        // 将左边的1全部移动到数组的最左边

        for (int i = 0; i < pos; i++) {
            if (bs[i] == 1) {
                sum++;
            }
        }
        for (int i = 0; i < pos; i++) {
            if (i < sum) {
                bs[i] = 1;
            } else {
                bs[i] = 0;
            }
        }

        // 检查是否所有的1都移动到了最右边
        for (int i = n - m; i < n; i++) {
            if (bs[i] == 0) {
                tempFlag = false;
                break;
            }
        }
        if (tempFlag == false) {
            flag = true;
        } else {
            flag = false;
        }

    } while (flag);
    result.add(print(bs, a, m));

    return result;
}

private static Object[] print(int[] bs, Object[] a, int m) {
    Object[] result = new Object[m];
    int pos = 0;
    for (int i = 0; i < bs.length; i++) {
        if (bs[i] == 1) {
            result[pos] = a[i];
            pos++;
        }
    }
    return result;
}

}

try this code :-

/*  Java code to generate all possible subsequences.
    Time Complexity O(n * 2^n) */

import java.math.BigInteger;

class Test
{
    static int arr[] = new int[]{1, 2, 3, 4};

    static void printSubsequences(int n)
    {
        /* Number of subsequences is (2**n -1)*/
        int opsize = (int)Math.pow(2, n);

        /* Run from counter 000..1 to 111..1*/
        for (int counter = 1; counter < opsize; counter++)
        {
            for (int j = 0; j < n; j++)
            {
                /* Check if jth bit in the counter is set
                    If set then print jth element from arr[] */

                if (BigInteger.valueOf(counter).testBit(j))
                    System.out.print(arr[j]+" ");
            }
            System.out.println();
        }
    }

    // Driver method to test the above function
    public static void main(String[] args) 
    {
        System.out.println("All Non-empty Subsequences");
        printSubsequences(arr.length);
    }
}

Didn't like or trust any of the previous answers so I added my own and enclosed some tests (mmm... te-e-ests):

int findSubArrayInArray(int startIdx, byte[] bytes, byte[] sub) {
    for (int bytesIdx = startIdx; bytesIdx < bytes.length; bytesIdx++) {
        boolean found = true;
        for (int subIdx = 0; subIdx < sub.length; subIdx++) {
            int compareIdx = bytesIdx + subIdx;
            if (bytes.length <= compareIdx || bytes[compareIdx] != sub[subIdx]) {
                found = false;
                break;
            }
        }
        if (found) {
            return bytesIdx;
        }
    }
    return -1;
}

Tests:

    assertEquals(5, findSubArrayInArray(1, new byte[] { 8, 5, 2, 8, 5, 8, 5, 2, 7 }, new byte[] { 8, 5, 2 }));
    assertEquals(7, findSubArrayInArray(1, new byte[] { 8, 5, 2, 8, 5, 8, 5, 2, 7 }, new byte[] { 2, 7 }));
    assertEquals(-1, findSubArrayInArray(1, new byte[] { 8, 5, 2, 8, 5, 8, 5, 2, 7 }, new byte[] { 2, 7, 6 }));

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