Reputation: 27
I made this method(interleave) that takes 3 arrays as input and then returns an array which has the elements of each array in order. If there in no element present in an array, then "-" is added t the final array.
Example: if these arrays are fed int the method - ["1";"2";"3"], ["4"], ["5";"6"] then it will return this array -
["1"; "4"; "5"; "2"; "-"; "6"; "3"; "-"; "-"]
But, when I am calling this I am getting nothing as an output.
static String[] interleave(String[] xs, String[] ys, String[] zs) {
int length1 = xs.length;
int length2 = ys.length;
int length3 = zs.length;
int larLength = 0;
if (((length1 > length2) && (length2 > length3) || ((length1 > length3) && (length3 > length2)))) {
larLength = length1;
}
else if (((length2 > length1) && (length1 > length3) || ((length1 > length3) && (length3 > length2)))) {
larLength = length2;
}
else if ((length3 > length2) && (length2 > length1)) {
larLength = length3;
}
String[] result = new String[larLength*larLength];
for(int i = 0; i < (larLength*larLength - 1); i++) {
if (xs[i] != null) {result[i] = xs[i];}
else {result[i] = "-";}
if (ys[i] != null) {result[i+1] = ys[i];}
else {result[i+1] = "-";}
if (zs[i] != null) {result[i+2] = zs[i];}
else {result[i+2] = "-";}
}
return result;
}
Upvotes: 0
Views: 93
Reputation: 370
You can replace the first part of the code with a simple Math.max(length1,length2,length3)
Here what you actually need is number of arrays * larLength
String[] result = new String[3*larLength];
And finally you need to fix the position at which you add the elements in your result array. It is not i
, i+1
and i+2
.
Instead the correct positions are:
first position to instert at :resultIndex = i*3
,
second position : resultIndex+1
third position : resultIndex+2
So your code would look like this:
String[] result = new String[3*larLength];
for(int i = 0; i < (larLength - 1); i++) {
int resultIndex = i*3;
if (xs[i] != null) {result[resultIndex] = xs[i];}
else {result[i] = "-";}
if (ys[i] != null) {result[resultIndex+1] = ys[i];}
else {result[i+1] = "-";}
if (zs[i] != null) {result[resultIndex+2] = zs[i];}
else {result[i+2] = "-";}
}
Upvotes: 1
Reputation: 1513
public class Dummy {
public static void main(String[] args) {
String xs[] = {"1", "2", "3"}, ys[] = {"4"} , zs[] = {"5", "6"};
int larLength = Math.max(Math.max(xs.length, ys.length),
Math.max(ys.length, zs.length));
int ind = 0;
String res[] = new String[3*larLength];
for (int i=0;i<larLength;i++) {
if (i<xs.length) res[ind++] = xs[i];
else res[ind++] = "-";
if (i<ys.length) res[ind++] = ys[i];
else res[ind++] = "-";
if (i<zs.length) res[ind++] = zs[i];
else res[ind++] = "-";
}
for (int i=0;i<res.length;i++) {
System.out.print(res[i]);
}
}
Upvotes: 0