3

I need to create an array that looks like this:

[0,0,1,1,2,2,3,3,4,4....]

Given my following code, how can I eliminate the counter?

int[] SomeArray = new int[24];
int counter = 0;
for(int x = 0 ; x < SomeArray.length-1 ; x++){
    SomeArray[x] = counter;
    SomeArray{x+1] = counter;
    counter++;
}
1
  • 1
    Current code only increase x by one step, so the output should be 0 1 2 3 4 5 6 .... Commented Dec 7, 2016 at 3:00

2 Answers 2

3

In Java 8+, you could use an IntStream.range(int, int) and map each value as desired. Something like,

int[] someArray = IntStream.range(0, 24).map(x -> {
    return x / 2;
}).toArray();

Also, please follow Java variable naming conventions (someArray, not SomeArray).

If you have to use Java 7 (or earlier), then you can do it with something like

int[] someArray = new int[24];
for (int i = 0; i < someArray.length; i++) {
    someArray[i] = i / 2;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Im using android studio so i need to use Java 6.
@דודיחיסין Edited. Next time, for better help faster, include relevant details like that in your question.
1

use increment x=x+2 as two indexes of array are being stored in every iteration

for(int x = 0 ; x < SomeArray.length-1 ; x+=2){
        SomeArray[x] = x/2;

        SomeArray[x+1] = x/2;
}

Comments

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.