Pankaj Kumar
Pankaj Kumar

Reputation: 41

How to store this pattern in Java arraylist?

I want to store the below array pattern in List, I am not understanding how to implement this as it has alternate increment.

  1. Increment the number by 399.
  2. Increment by 1

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

Answers (2)

Pankaj Kumar
Pankaj Kumar

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

sabraship
sabraship

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

Related Questions