Ques: Given an array of ints, return true if the array contains either 3 even or 3 odd values all next to each other.
Ans:
package oddorevenin.array;
public class OddorEveninArray {
public static void main(String[] args) {
int[] nums = {2, 2, 2, 5, 9};
System.out.println("Nunber=" + modThree(nums));
}
public static boolean modThree(int[] nums) {
int ecount = 0;
int ocount = 0;
int oloop = 0;
int eloop = 0;
for (int i = 0; i < nums.length; i++) {
oloop = i;
if (nums[oloop] % 2 == 1) {
for (int j = 0; j < 3; j++) {
if (j + i > nums.length - 1) {
break;
}
if (nums[j + i] % 2 == 1) {
ocount++;
oloop++;
}
if (ocount == 3) {
break;
}
}
if (ocount < 3) {
ocount = 0;
}
}
if (ocount == 3) {
break;
}
}
/////////////////////////Starting the Even loop
for (int i = 0; i < nums.length; i++) {
eloop = i;
if (nums[eloop] % 2 == 0) {
for (int j = 0; j < 3; j++) {
if (j + i > nums.length - 1) {
break;
}
if (nums[j + i] % 2 == 0) {
ecount++;
eloop++;
}
if (ecount == 3) {
break;
}
}
if (ecount < 3) {
ecount = 0;
}
}
if (ecount == 3) {
break;
}
}
return (ocount == 3 || ecount == 3) ? true : false;
}
}
Ans:
package oddorevenin.array;
public class OddorEveninArray {
public static void main(String[] args) {
int[] nums = {2, 2, 2, 5, 9};
System.out.println("Nunber=" + modThree(nums));
}
public static boolean modThree(int[] nums) {
int ecount = 0;
int ocount = 0;
int oloop = 0;
int eloop = 0;
for (int i = 0; i < nums.length; i++) {
oloop = i;
if (nums[oloop] % 2 == 1) {
for (int j = 0; j < 3; j++) {
if (j + i > nums.length - 1) {
break;
}
if (nums[j + i] % 2 == 1) {
ocount++;
oloop++;
}
if (ocount == 3) {
break;
}
}
if (ocount < 3) {
ocount = 0;
}
}
if (ocount == 3) {
break;
}
}
/////////////////////////Starting the Even loop
for (int i = 0; i < nums.length; i++) {
eloop = i;
if (nums[eloop] % 2 == 0) {
for (int j = 0; j < 3; j++) {
if (j + i > nums.length - 1) {
break;
}
if (nums[j + i] % 2 == 0) {
ecount++;
eloop++;
}
if (ecount == 3) {
break;
}
}
if (ecount < 3) {
ecount = 0;
}
}
if (ecount == 3) {
break;
}
}
return (ocount == 3 || ecount == 3) ? true : false;
}
}
No comments:
Post a Comment