I'm trying to find the recursive function for this problem, to be more clear:
- Input = [8, 4, 3, 4}
- n = 3
- Output = [8, 8, 8, 4, 4, 4, 3, 3, 3, 4, 4, 4]
I've solved it using iteration and loop, but since I was just introduced to recursive methods, I'm still struggling pretty hard with this problem in particular. This is my iterative solution for it.
public class repeatElement {
public static void main(String[] args) {
int[] a = {1, 2, 3};
int n, j, i;
n = Integer.parseInt(JOptionPane.showInputDialog("Enter n"));
int[] b = new int[a.length * n];
for (i = 0; i < a.length; i++) {
for (j = n*i; j < n*(i+1); j++) {
if (j % n == 0) {
b[j] = a[i];
}
if (j % n != 0) {
b[j] = a[i];
}
}
}
JOptionPane.showMessageDialog(null, Arrays.toString(b));
}