Problem:
Given 2 int arrays, a and b, return a new array length 2 containing, as much as will fit, the elements from a followed by the elements from b. The arrays may be any length, including 0, but there will be 2 or more elements available between the 2 arrays.
make2({4, 5}, {1, 2, 3}) → {4, 5}
make2({4}, {1, 2, 3}) → {4, 1}
make2({}, {1, 2}) → {1, 2}
Solution:
public int[] make2(int[] a, int[] b) { int[] temp = new int[2]; int index=0; for(int i=0; i<a.length; i++) if(index<2){ temp[index]=a[i]; index++; } for(int i=0; i<b.length; i++) if(index<2){ temp[index]=b[i]; index++; } return temp; }
Site's solution is not following directions, you are not allowed to use loops. It's a logic problem.
ReplyDeletethe best as the second
Deletepublic int[] make2(int[] a, int[] b) {
if(a.length>1)
return new int[] {a[0],a[1]};
if(a.length==0)
return new int[] {b[0],b[1]};
if(a.length==1)
return new int[] {a[0],b[0]};
return a;
}
EASIEST:
ReplyDeletepublic int[] make2(int[] a, int[] b) {
if(a.length == 0){
return new int[] { b[0], b[1] };
}
if(a.length == 1){
return new int[] { a[0], b[0] };
}
if(a.length >=2){
return new int[] { a[0], a[1] };
}
return a;
}
public int[] make2(int[] a, int[] b) {
ReplyDeleteint re[]=new int[2];
if(a.length>1)
{
re[0]=a[0];
re[1]=a[1];
return re;
}
else if(a.length>0)
{
re[0]=a[0];
re[1]=b[0];
return re;
}
else if(a.length==0)
{
re[0]=b[0];
re[1]=b[1];
return re;
}
else{
return b;
}
}
ewds
ReplyDeletepublic int[] make2(int[] a, int[] b) {
ReplyDeleteint [] newInt = new int [2];
if(a.length > 1){
newInt[0] = a[0];
newInt[1] = a[1];
}else if(a.length == 1 && b.length > 1){
newInt[0] = a[0];
newInt[1] = b[0];
}else if(a.length == 1 && b.length == 1){
newInt[0] = a[0];
newInt[1] = b[0];
}else if(a.length == 0 && b.length >1){
newInt[0] = b[0];
newInt[1] = b[1];
}
return newInt;
}
public int[] make2(int[] a, int[] b)
ReplyDelete{
int[] A = new int[2];
int[] temp = new int[a.length+b.length];
int counter = 0;
for(int i = 0;i<a.length;i++)
{
temp[counter++] = a[i];
}
for(int i = 0;i<b.length;i++)
{
temp[counter++] = b[i];
}
for(int i = 0;i<2;i++){
A[i] = temp[i];
}
return temp.;
}