-1

I'm looking for an algorithm to fill an array of a specific size with the contents of a vararg, repeating the last element of the vararg until the array is full.

public static <T> T[] fillWithRepeat(int length, T... elements) {
    // make array of length "length" and fill with contents of "elements"
}

Does anyone know a good algorithm for this?

HYBR1D
  • 446
  • 2
  • 6
  • 19
  • 1
    A simple while-loop? – Hulk Jan 23 '19 at 14:46
  • If you don't want to write the loop yourself, use [Arrays.fill](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html#fill(java.lang.Object%5B%5D,int,int,java.lang.Object)) – Hulk Jan 23 '19 at 14:48
  • 1
    I always appreciate when users quickly accept answers, even when its not mine ;-) – GhostCat Jan 23 '19 at 15:18

2 Answers2

4

As the question doesn't include any attempt of solving the problem itself, I assume homework, thus the answer is pseudo code only:

  • create a new array results of length length
  • iterate index from 0 to length
  • establish an index2 variable that runs from 0 to elements.length
  • assign ressult[index] = elements[index2]
  • either increase index2, or when it reaches elements.length-1, keep it at that value

For creating a "generic" array, see here.

And of course, user Hulk is correct (again), there are utility methods Arrays.fill() and for newer Javas Array.copyOf() that you should consider using.

GhostCat
  • 127,190
  • 21
  • 146
  • 218
  • One thing, I can't create an array of a generic type. – HYBR1D Jan 23 '19 at 14:49
  • Only the last element in the vararg should be repeated, though. – HYBR1D Jan 23 '19 at 14:50
  • 1
    @HYBR1D see also [Arrays.copyOf](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html#copyOf(T%5B%5D,int)) - you want to copy most of the array, and then fill the remainder – Hulk Jan 23 '19 at 14:52
1

Here's the algorithm. It also caters for the Generic instantiation problem when you will need to instantiate an array of type T

public static <T> T[] fillWithRepeat(int length, T... elements) {

    List<T> output = new ArrayList<>(Arrays.asList(elements));
    for(int i = 0; i < length - elements.length; i++){
        output.add(elements[elements.length - 1]);
    }

    return output.toArray(elements);
}
Eslam Nawara
  • 517
  • 2
  • 7