4. inil] runDecodefin] a) that takes an array that consists of a series of eleme
ID: 3723048 • Letter: 4
Question
4. inil] runDecodefin] a) that takes an array that consists of a series of element values following 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 correct length. (You can assume that the length of the parameter array is even. A run length can never be negative, although it can be zero. As a possibly tricky edge case, the result array could even end up being empty, if every run has zero length!)Explanation / Answer
import java.util.*;
import java.util.Scanner;
class Ele{
public static int[] runDecode(int[] a){
int[] r = new int[a.length];
int i=0,j=0,k=0;
for(i=0,k=0;i<a.length;){
for(j=0;j<a[i];j++){
r[k]=a[i+1];
k=k+1;
}
i=i+2;
}
return r;
}
public static void main(String[] args){
int[] a ={3,8,1,-7,0,42,4,-3};
int[] b= runDecode(a);
for(int i=0;i<b.length;i++){
System.out.print(b[i]+" ");
}
}
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.