You need a nested for-loop. You append span
-elements from arr1
and arr2
at a time, with span
increasing from 1. This code only works if N
is a triangular number; otherwise the last element will be "incomplete" and as of now this code doesn't handle it (and would throw ArrayIndexOutOfBoundsException
).
String[] arr1 = { "a1", "a2", "a3", "a4", "a5", "a6" };
String[] arr2 = { "b1", "b2", "b3", "b4", "b5", "b6" };
int N = arr1.length;
// here we assume that N == arr2.length, and N is triangular
StringBuilder sb = new StringBuilder();
for (int start = 0, span = 1; ; span++) {
for (int i = 0; i < span; i++) {
sb.append(arr1[start + i]);
}
for (int i = 0; i < span; i++) {
sb.append(arr2[start + i]);
}
start += span;
if (start == N) break;
sb.append(",");
}
System.out.println(sb);
// prints "a1b1,a2a3b2b3,a4a5a6b4b5b6"
The logic
To understand just the underlying logic, perhaps we can start with something simpler:
int start = 0;
int N = 8;
int span = 1;
while (start < N) {
System.out.println("span = " + span);
for (int i = 0; i < span; i++) {
System.out.println(start + i);
}
start += span;
span++;
}
This prints:
span = 1
0
span = 2
1
2
span = 3
3
4
5
span = 4
6
7
8
9
You should understand how the nested loop structure works. Again, note that even though N = 8
(which is not a triangular number), the loop actually prints 10 numbers (which is a triangular number). You can work on this snippet first, try to modify it so that it will only print N
numbers regardless of whether or not it's a triangular number, and then adapt the same technique to the original problem.
You can also work on this snippet to print, say, "next!"
before each span
line, except the first. That would be the same logic to include the comma in the original problem.
Good luck!