Reputation: 49
I inserted 25 elements in an arraylist named "l".Next i am adding first five elements and store the total into an array first position(a[0]).Then again adding next five elements and store the total into an array second position(a[1]).Likewise it goes on.Then atlast i print the array "a".I tried for loop for this.
for (int i = 0; i<5; i++) {
total = total + l.get(i);
}
System.out.println("1 " + total);
a[0] = total;
total = 0;
for (int i = 5; i<10; i++) {
total = total + l.get(i);
}
System.out.println("2 " + total);
a[1] = total;
total = 0;
for (int i = 10; i<15; i++) {
total = total + l.get(i);
}
System.out.println("3 " + total);
a[2] = total;
total = 0;
for (int i = 15; i<20; i++) {
total = total + l.get(i);
}
System.out.println("4 " + total);
a[3] = total;
total = 0;
for (int i = 20; i<25; i++) {
total = total + l.get(i);
}
System.out.println("5 " + total);
a[4] = total;
}
for(int i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
for eg : If the arraylist contains the elements("1,1,0,8,4,6,6,1,0,1,4,1,1,1,6,6,4,1,0,8,8,3,8,1,0") then it prints the output as " 14 14 13 19 20" and this code prints correctly.I used 5 for loops to do this,Is there is any other simple way to do this?If there is then tell me what logic can i use?
Upvotes: 0
Views: 49
Reputation: 3180
There is a main issue with your code, you are only able to process arrays of size 25 (at the most). You should be using loops to get the behaviour you want. (Using loops also has the benefit of not reusing code over and over again)
Look at your code, what seems to be repeated over and over again?
It seems like the section:
for (int i = 0; i<5; i++) {
total = total + l.get(i);
}
System.out.println("1 " + total);
a[0] = total;
total = 0;
is repeated 5 times! You should always aim to write the least amount of code
You can generalize your solution to the following:
for (int chunk = 0; chunk < 5; chunk ++) {
for (int i = 0; i < 5; i++) {
total = total + l.get(i + chunk * 5);
}
System.out.println(chunk + " " + total);
a[chunk] = total;
total = 0;
}
Instead of using array
for the results, you can use another array list
Like so:
List<Integer> results = new ArrayList<Integer>();
for (int i = 0; i < l.size(); i++) {
int chunk = i / 5;
if (chunk >= results.size())
results.add(l.get(i));
else
results.set(chunk, l.get(i) + results.get(chunk));
}
for (int i = 0; i < results.size(); i++) {
System.out.println(i + " " + results.get(i));
}
Upvotes: 1