Problem:
Start with 2 int arrays, a and b, of any length. Return how many of the arrays have 1 as their first element.
start1({1, 2, 3}, {1, 3}) → 2
start1({7, 2, 3}, {1}) → 1
start1({1, 2}, {}) → 1
Solution:
public int start1(int[] a, int[] b) { int count = 0; if (a.length != 0) { if (a[0]== 1) count++; } if (b.length != 0) { if (b[0]== 1) count++; } return count; }
public int start1(int[] a, int[] b) {
ReplyDeleteint result = 0;
if (a.length > 0 && a[0] == 1)
result++;
if (b.length>0 && b[0]== 1)
result++;
return result;
}
2-Line Solution:
ReplyDeletepublic int start1(int[] a, int[] b) {
int[][] ab = {a,b};
return (int)Arrays.stream(ab).filter(arr -> arr.length > 0 && arr[0] == 1).count();
}
Start with 2 int arrays, a and b, of any length. Return how many of the arrays have 1 as their first element.
ReplyDeletehow to do it?
This is great, but I have a questions about the (int) in this solution: Is the "(int)" used to specify that this will be a stream of ints? Or is it telling stream that this is an array of ints? Thanks
ReplyDeletepublic int[] biggerTwo(int[] a, int[] b) {
ReplyDeleteint sumA = a[0]+a[1];
int sumB = b[0]+b[1];
if(sumA<sumB)
return b;
else
return a;
}
bro your answer is not correct. and you answered completely different questions.
Deletepublic int start1(int[] a, int[] b) {
ReplyDeleteint one = 0;
if(a.length != 0 && a[0]==1)
{
one++;
}
if(b.length != 0 && b[0]==1)
{
one++;
}
return one;
}
public int start1(int[] a, int[] b) {
ReplyDeleteint count = 0;
int[][] arrays = new int[][]{a, b};
for(int i = 0; i < arrays.length; i++) {
if(arrays[i].length > 0 && arrays[i][0] == 1) {
count++;
}
}
return count;
}