I'm working on the following problem where I have to create said method:
int[] runLength(int[] a) that takes an array that consists of a series of element values followed by the lengths of the run of those elements, listed in alternating locations. This method creates and returns a new array that contains these elements, each element repeated the number of times given by its run length. For example, when called with the array {3, 8, 1, -7, 0, 42, 4, -3} (read this out loud as “three eights, one minus seven, zero forty-twos, and four minus threes”), your method would create and return the array {8, 8, 8, -7, -3, -3, -3, -3}. Again, make sure that the array returned by your method has the exact right length.
public int[] runLength(int[] a) {
int[] answer;
for(int i = 0; i <= answer.length; i++) {
if(i % 2 != 0) {
for(int j = 0; j < i; j++) {
// answer.push(i+1); is what I would do in Javascript
}
}
}
}
I actually wrote this program in javascript first because i'm more familiar with it then translated into Java after (still sure I have a few errors with the for loop maybe. I'm actually steadily learning Java at the moment but realized that obviously Java has something different then the push() method when adding new values into an array. How exactly would I do this in Java then?