请帮我做这个总和,并像这样拆分数组。 [英] Please help me to do this sum and split array like this.

查看:82
本文介绍了请帮我做这个总和,并像这样拆分数组。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

arr[]={1,3,2,4,6,7,8,9,10, 11,12,16,5,8,7,8,4,6};
split=2; // the arr[] will be divide in 2(no of splits) parts each with equal elements split=1,2,3...n
skip=2; // skip is no of element to be skipped. skip=1,2,3...n
size of res[] should be accordingly.
then
res[0]=15 //1+4+8
res[1]=18//3+6+9
res[2]=19 //2+7+10
res[3]=24 //11+5+8
res[4]= 24 //12+8+4
res[5]= 29//16+7+6



和明智的拆分可以是1到n。

arr [] = {1,2,3 ... n}元素

这应该是动态的。

请帮我这样做。

谢谢



我尝试了什么:




and like wise split can be 1 to n.
arr[]={1,2,3...n} elements
This should be dynamically.
Please help me to do this.
Thanks

What I have tried:

int[] arr = { 1, 3, 2, 4, 6, 7, 8, 8 };  
int split = 2;  
int counter1 = 0;  
int counter = arr.Length / (split);  
int[] tempArr = new int[counter];  
  
for (int idx = 0; idx < counter; idx++)  
{  
    if (idx % split == 0)  
    {  
        counter1 = idx * split;  
    }  
    else  
    {  
        counter1 = idx * split - 1;  
    }  
  
    tempArr[idx] = arr[counter1] + arr[counter1 + split];  
}



我试过这个,但它只跳过1个元素,分裂也没有运行真正的


I have tried this but it skips only 1 elements also splits is not running true

推荐答案

你提问并且你的例子不合情理。无论如何,如果我理解正确,你想创建一个新的int数组,其元素是现有数组的特定间隔(跳过)的int元素的总和。显然,你需要一个内部for循环,其起始索引将是现有数组中的下一个元素,增量值是skip + 1,以便拾取和求和现有数组中的元素。查看此示例并根据您的需要进行调整:

You question and your example do not tally. Anyway, if I understand you correctly, you wanted to create a new int array whose elements are the sum of int elements at certain interval (skip) of an existing array. Apparently, you need an inner for loop whose start index will be the next element in the existing array and the incremental value is skip+1 so as to pick up and sum the elements in the existing array . Check out this example and adapt it to your need:
using System;

public class Program
{
	public static void Main()
	{
		int[] arr =
		{
			1,3,2,4,6,7,8,9,10, 11,12,16,5,8,7,8,4,6,7
		}
		;
		int split = 2;
		int counter = arr.Length / (split);
		int skip = 2;
		int[] tempArr = new int[counter];
		for (int idx = 0; idx < counter; idx++)
		{
			int sum = 0;
			for (int i = idx; i < arr.Length; i = i + skip + 1)
			{
				sum += arr[i];
			}

			tempArr[idx] = sum;
		}

		for (int j = 0; j < tempArr.Length; j++)
		{
			Console.WriteLine(tempArr[j]);
		}
	}
}


这篇关于请帮我做这个总和,并像这样拆分数组。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆