Reputation: 41
I want to store the below array pattern in List, I am not understanding how to implement this as it has alternate increment.
and continue the above 2 steps for a certain length of numbers. If someone can guide me for the logic with simple OOPs concepts
0, 400, 401, 800, 801, 1200, 1201, 1600, 1601, 2000
Upvotes: 0
Views: 282
Reputation: 41
Figured it out, this is what I wrote now, and it workds
int pages = 8;
List<Integer> numArray = new ArrayList<Integer>();
numArray.add(0);
boolean incrementFlag = false;
int i = 400;
for (int j = 0; j < (pages-1); j++) {
numArray.add(i);
if (incrementFlag)
i += 399;
else
i += 1;
incrementFlag = !incrementFlag;
}
Upvotes: 0
Reputation: 99
You could also do something like this:
//add the first item outside of the loop, so that you can access the previous item within it
list.add(1)
//loop through the list in increments of 2
for (int i = 1; i < length; i += 2) {
list.add(list.get(i - 1) + 399);
list.add(list.get(i) + 1);
}
Upvotes: 1