0

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

6
  • 1
    What have you tried? Seems like you just need to alternate the increment each time through the loop. Commented Jul 11, 2020 at 15:45
  • I have written to implement by 399 but how to alternate is what I can't think of Commented Jul 11, 2020 at 15:49
  • 2
    Shouldn't your list be 0, 399, 400, 799, 800...? Otherwise you're incrementing by 400, then 1. Commented Jul 11, 2020 at 15:51
  • 1
    Seems like you're new to programming, and if true, I guess everyone will agree that you should give it a though yourself and not ask for it on Stack Overflow. In the end if at all you don't find a solution yourself, you can google about alternating series and see how it's done. Commented Jul 11, 2020 at 15:51
  • How would you alternate IRL? You’d probably remember what you alternated by the previous iteration, and switch to the other one based on what you did last time. Commented Jul 11, 2020 at 15:54

2 Answers 2

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

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;

    }

2 Comments

Why do you add to i?
Glad you worked out a solution. The flag is redundant; you could just use the increment value as the flag since you can check its value, but that’s an implementation detail. You could also use a ternary op to select the value to add, but that’s another minor implementation detail. Good work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.