0

Hey I would like to fill an array from elements from another array. For example (below) And array b should be filled with elements in this order from array b. Is there some method for this? I only know Arrays.fill ( but it's for 1 element). The table a is variable, not static !

int a[1,2,3,4];

int b[] = new int[100];
int b[] = {1,2,3,4,1,2,3,4,...}
2
  • you want to repeat a in b N time is that what you want? Commented Jul 20, 2018 at 17:31
  • No.Fill b with a elements to b.lenth. Commented Jul 20, 2018 at 17:34

4 Answers 4

4

You can use System.arraycopy() method. Which copies a source array from a specific beginning position to the destination array from the mentioned position.

e.g. copy array a 25 times to fill in b.

int[] a = {1, 2, 3, 4};
int[] b = new int[100];
for (int i = 0; i < b.length; i += a.length) {
    System.arraycopy(a, 0, b, i, 4);
}
Sign up to request clarification or add additional context in comments.

1 Comment

This will throw and exception if the length of "b" is not evenly divisible by the length of "a".
0

I would imagine a simple for loop that cycles through the first array and adds to the second would be a basic solution without invoking a method you might not be familiar with.

    int a[1,2,3,4];
    int b[]  = new int[100];
    int j = 0;
    for (int i = 0; i < b.length; i++) 
    {
       if(j == 4) 
       { 
           j = 0; 
       }
       int n = a[j];
       b[i] = n;
       j++; 
    }

Or you can have it check the array length if the size of array "a" changes

    int a[1,2,3,4];
    int b[]  = new int[100];
    int j = 0;
    for (int i = 0; i < b.length; i++) 
    {
       if(j == a.length) 
       { 
           j = 0; 
       }
       int n = a[j];
       b[i] = n;
       j++; 
    }

Comments

0

Here's a way to do it with Streams

int b[] = Stream.iterate(0, i -> i == a.length - 1 ? 0 : i + 1)
            .limit(100)
            .mapToInt(i -> a[i])
            .toArray();

Stream.iterate(0, i -> i == a.length - 1 ? 0 : i + 1): Starts with 0 as the seed and produces a stream of Integers incrementally. We reset/restart once the index reaches the end of the array.

limit(100): Limit to 100 elements as the source of the Stream is infinite.

.mapToInt(i -> a[i]): Convert the incoming Integer index to an int by getting the element at the index from array a.

.toArray(): Collect the individual elements to an int[].

Comments

0

You can accomplish this with a for loop and the modulus operator:

    for (int i = 0; i < b.length; i ++) {
        b[i] = a[i % a.length];
    }

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.