java - 使用索引点在多个点拆分数组

标签 java arrays random numbers

我遇到过很多使用索引点将给定数组或数组列表拆分为两个数组或多个数组的示例。我试过了,它们工作得很好。我的问题是,是否可以根据给定的索引点将数组拆分为多个不同 block 大小的数组?

例如:

array[] = {10,1,2,3,10,4,5,10,6,7,10,8,10};
index_value = 10;

那么输出应该是四个数组,例如:

arr1[] = {1,2,3}
arr2[] = {4,5}
arr3[] = {6,7}
arr4[] = {8}

当给定的数组是静态的且没有任何更改时,我能够拆分它们并显示结果。但是对于具有随机数和随机大小的数组实现相同的方法很困难。我需要将分割值存储在许多子数组中,而不仅仅是打印值。

最佳答案

对于此解决方案,index_value 不必位于数组的开头或结尾:

int[] arr = new int[]{10,10,1,10,1,2,3,10,4,5,10,6,7,10,8,10,9,8,7,6,5,4,3,10,1,2,3,4,5,6,7,10,5,4,10,10};
int index_value = 10;

/** walk through the array and create the arraylist of arraylists */
ArrayList<ArrayList<Integer>> al = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> currAl = null;
for (int i=0; i < arr.length; i++) {
    if (arr[i] == index_value) {
        if (currAl != null && currAl.size() > 0)
            al.add(currAl);
        currAl = new ArrayList<Integer>();
    } else {
        if (currAl == null)
            currAl = new ArrayList<Integer>();
        currAl.add(arr[i]);
    }
}
if (arr[arr.length-1]!= index_value && currAl.size() > 0) {
    al.add(currAl);
}

/** print out the arraylist of arraylists */
for (int i=0; i < al.size(); i++) {
    currAl = al.get(i);
    for (int j=0; j < currAl.size(); j++) {
        System.out.print(currAl.get(j) + " ");
    }
    System.out.println();
}

关于java - 使用索引点在多个点拆分数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22565684/

相关文章:

java arraylist 对象的总和

JAVA EE 7 First cup教程,无法安装Glassfish 4更新中心

c# - 有什么方法可以匹配 Visual Fox Pro 和 C#.Net 的 RAND(INT) 方法

c++ - 在C++中向数组添加索引和指定数字

php - 从 PHP 访问 CryptGenRandom

function - 为什么我不能用两个 i32 参数调用 gen_range?

java - Mockito spy 测试

java - 重命名 Spring 中 MappingJacksonJsonView 使用的 JSON 字段

javascript - ES5 定义不可更改的数组/属性值

javascript - 在数组内的对象中搜索