如何用另一个大小不同的数组中的元素填充数组? 将不存在的索引保留为零

如何解决如何用另一个大小不同的数组中的元素填充数组? 将不存在的索引保留为零

场景1:如果主数组长度为

声明:

int[] mainArray = new int[] { 1,2,3,4,5 } // no minimum number of elements
int[] arrayOne = new int[] { 0,0 }; // must have 8 elements

我想将mainArray中的值添加到arrayOne中,而备用元素保留为零。

所需的数组

int[] arrayOne = new int[] { 1,5,0 }; // must have 8 elements

场景2:如果主数组长度> 8

声明:

int[] mainArray = new int[] { 1,6,7,8,9,10 } // no minimum number of elements
int[] arrayOne = new int[] { 0,0 }; // must have 8 elements
int[] arrayTwo = new int[] { 0,0 }; // must have 8 elements

我想将mainArray中的前8个值添加到arrayOne中,然后将剩下的值添加到arrayTwo中,将其他索引保留为零(您将在第二个数组的右侧看到9和10,所以arrayOne是从左到右,arrayTwo是从右到左。如果存在arrayThree,它将再次从左到右)

所需的数组:

int[] arrayOne = new int[] { 1,8 }; // must have 8 elements
int[] arrayTwo = new int[] { 0,10,9 }; // must have 8 elements

解决方法

您可以使用

        Arrays.fill(arr,0);

对于后续数组,您可以从结束索引开始-剩余项的长度以8为模,得出必须填充的其他数组数。

,

首先,为了演示起见,我假设您进行了数组初始化。如果没有,您可以像这样创建任何自定义数组: int [] arrayOne = {n,n,n,n,n,n}; (在大括号之间使用逗号分隔的任意数量的元素)

要实现您想做的事情,您需要使用一堆循环。这就是我要解决的方法:

if (mainArray.length <= 8) {
    for (int i = 0; i < mainArray.length; i++) {
        arrayOne[i] = mainArray[i];
    } // very standard loop for copying and pasting elements
} else {
    int direction = 1; // 1 means left to right,-1 means right to left
    int shortIndex = 0; // modified as to return back to index zero when equal to 8    
    for (int i = 0; i < mainArray.length; i++) {
        if (i + 1 % 8 == 0 && i != 0) { // switching directions when length 8 is reached
            direction *= -1;
        }

        if (direction == 1) {
            ArrayOne[shortIndex] = mainArray[i];
            shortIndex++;
        } else if (direction == -1) {
            ArrayTwo[shortIndex] = mainArray[I];
            shortIndex--;
        }
    }
}

这实际上只是我草拟了一个基本概念,因为我尚未实际测试过此代码,但是我希望这可以使您更好地理解如何解决它。同样,这可能仅在您只需要两个数组而不是3个或更多数组的情况下有效。

基本上,如果mainArray的长度大于8,您将需要一个附加的计数器变量以及某种变量,这些变量可在arrayOne达到最大值并准备好移至下一个变量时切换条件。发生这种情况时,我切换条件变量(方向),以便我的循环知道要遍历数组的方向。

shortIndex是我正在谈论的第二个计数器变量。它将跟随变量“ i”,每次迭代递增1,直到到达索引7(与长度8相同),然后一旦方向更改,它将从索引7(再次与长度8相同)开始,并从在那里。

我希望这个解释不要太混乱了

,

为此,我使用List<int[]>来存储数组。遍历mainArray并依次复制指定的内容,直到没有剩余的元素为止。交替反转列表的子列表。

mainArray = new int[] { 1,2,3,4,5,6,7,8,9,10,11,12,13,14 }; // no minimum number of elements

List<int[]> arrays = new ArrayList<>();
int size = 5;
int begin = 0;
// Copy the array,rounding up to a multiple of size,filling in with 0 value.
mainArray = Arrays.copyOf(mainArray,mainArray.length + (size - (mainArray.length % size)));

// convert the mainArray to a list.  Need this to use subList and reverse.
List<Integer> vals = IntStream.of(mainArray).boxed().collect(Collectors.toList());

boolean reverse = false;
while (begin < vals.size()) {
    // get the first group of numbers,going from left to right.
    List<Integer> sublist = vals.subList(begin,begin+size);
    // check if time to reverse the sublist.
    if (reverse) {
        Collections.reverse(sublist);
    }
    // now just copy the sublist to an array and store away.
    arrays.add(sublist.stream().mapToInt(Integer::intValue).toArray());
    // update state
    reverse = !reverse;
    begin+=size;
}
    
for (int[] a : arrays) {
    System.out.println(Arrays.toString(a));
}

打印尺寸为5

[1,5]
[10,6]
[11,14,0]

对于大小= 8

[1,8]
[0,9]

这是另一个仅使用List返回构造数组的方法。只需每隔一次迭代就更改填充方向。

public static List<int[]> fill(int[] main,int size) {
    List<int[]> arrays = new ArrayList<>();
    main = Arrays.copyOf(main,main.length + (size - (main.length % size)));
    int count = (main.length/size)+1;
    int ainc = 0;
    while (count-- > 1) {
        int[] temp = new int[size];
        arrays.add(temp);
        boolean reverse = count % 2 == 0;
        int idx = reverse ? size - 1 : 0;
        int inc = reverse ? -1 : 1;
        
        for (int i = 0; i < size; i++) {
            temp[idx] = main[ainc++];
            idx += inc;
        }
    }
    return arrays;
}
,

尝试一下。

static int copy(int[] mainArray,int start,int[] array) {
    int mainArrayLength = mainArray.length;
    if (start >= mainArrayLength) return start;
    int length = Math.min(mainArrayLength - start,array.length);
    System.arraycopy(mainArray,start,array,length);
    return start + length;
}

static void reverse(int[] array) {
    for (int i = 0,j = array.length - 1; i < j; ++i,--j) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}

static void copy(int[] mainArray,int[] arrayOne,int[] arrayTwo) {
    int start = copy(mainArray,arrayOne);
    copy(mainArray,arrayTwo);
    reverse(arrayTwo);
}

    int[] mainArray = {1,10};
    int[] arrayOne = {0,0};
    int[] arrayTwo = {0,0};
    copy(mainArray,arrayOne,arrayTwo);
    System.out.println("arrayOne = " + Arrays.toString(arrayOne));
    System.out.println("arrayTwo = " + Arrays.toString(arrayTwo));

输出

arrayOne = [1,8]
arrayTwo = [0,9]

如果要复制到两个以上的数组而不反转它们,请执行此操作。

static void copy(int[] mainArray,int[]... arrays) {
    int start = 0;
    for (int[] array : arrays)
        start = copy(mainArray,array);
}

int[] mainArray = {1,13};
int[] arrayOne = {0,0};
int[] arrayTwo = {0,0};
int[] arrayThree = {0,0};
copy(mainArray,arrayTwo,arrayThree);
System.out.println("arrayOne = " + Arrays.toString(arrayOne));
System.out.println("arrayTwo = " + Arrays.toString(arrayTwo));
System.out.println("arrayThree = " + Arrays.toString(arrayThree));

输出

arrayOne = [1,5]
arrayTwo = [6,10]
arrayThree = [11,0]

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-