A Bean array is defined to be an integer array where for every value n in the array, there is also an element
2n, 2n+1 or n/2 in the array.
For example, {4, 9, 8} is a Bean array because
For 4, 8 is present; for 9, 4 is present; for 8, 4 is present.
Other Bean arrays include {2, 2, 5, 11, 23}, {7, 7, 3, 6} and {0}.
The array {3, 8, 4} is not a Bean array because of the value 3 which requires that the array contains either the value 6, 7 or 1 and none of these values are in the array.
Write a function named isBean that returns 1 if its array argument is a Bean array. Otherwise it returns a 0.
If you are programming in Java or C#, the function signature is
int isBean(int[ ] a)
If you are programming in C or C++, the function signature is
int isBean(int a[ ], int len) where len is the number of elements in the array.
solution :
first Way
For example, {4, 9, 8} is a Bean array because
For 4, 8 is present; for 9, 4 is present; for 8, 4 is present.
Other Bean arrays include {2, 2, 5, 11, 23}, {7, 7, 3, 6} and {0}.
The array {3, 8, 4} is not a Bean array because of the value 3 which requires that the array contains either the value 6, 7 or 1 and none of these values are in the array.
Write a function named isBean that returns 1 if its array argument is a Bean array. Otherwise it returns a 0.
If you are programming in Java or C#, the function signature is
int isBean(int[ ] a)
If you are programming in C or C++, the function signature is
int isBean(int a[ ], int len) where len is the number of elements in the array.
solution :
first Way
public static int isBean(int[] a) { int isBean = 1; for (int i = 0; i < a.Length; i++) { int isValid = 0; for (int j = 0; j < a.Length; j++) { if (a[i] == 2 * a[j] || a[i] == 2 * a[j] + 1 || a[i] == a[j] / 2) { isValid = 1; break; } } if (isValid == 0) isBean = 0; } return isBean; }Second Way
public static int isBean(int [] a) { int i, j,x,y,z; bool isMeera = true, step = false; for(i=0;i<a.Length;i++) { step = false; for(j=0;j<a.Length;j++) { x = 2 *a[j]; y = 2 * a[j] + 1; z = a[j]/2; if (a[i] == x || a[i]==y || a[i]==z) step = true; } if(j==a.Length && step==false) { isMeera =false; break; } } return isMeera ==true ? 1 : 0; }
Thanks for the effort, i think this is a wrong approach since all elements have to satisfy the conditions of 2n and 2n + 1 yet in your approach they will only have to satisfy one condition.
ReplyDeleteThanks 4 the effort.
ReplyDeletethere is a bug in both the codes
the return 1 for {} string.
public static int isBean(int[] a){
ReplyDeleteint count = 0;
for (int i = 0; i < a.length; i++){
for (int j = 0; j < a.length; j++){
if (a[i] * 2 == a[j] || (a[i] * 2) + 1 == a[j] || a[i] / 2 == a[j]){
count += 1;
break;
}
}
if(count == 0){return 0;}
}
return 1;
}