How i can check if all elements in the arrays are even or odd?
For the evens I try with this:
public boolean isEvens(int[] array) {
for (int i = 0; i<array.length;i++) {
if ( i % 2 == 0) {
return true;
}
else {
return false;
}
}
}
But there is error......
Thnx in advance !
You should check the array elements, not the array indices.
You shouldn't return true before checking all the elements of the array.
You can use a counter to count the number of odds or evens, or a boolean to determine if there are any odds or evens.
For example:
public boolean allEven(int[] array) {
for (int i = 0; i<array.length; i++) {
if (array[i] % 2 != 0) {
return false;
}
}
return true;
}
To check whether all are even or all are odd:
public boolean allEvenOrAllOdd(int[] array) {
boolean hasOdd = false;
boolean hasEven = false;
for (int i = 0; i<array.length; i++) {
if (array[i] % 2 == 0) {
hasEven = true;
if (hasOdd) { // has both odds and evens
return false;
}
} else {
hasOdd = true;
if (hasEven) { // has both odds and evens
return false;
}
}
}
return true; // either all elements are odd or all elements are even
}
Since java 8 it's a good practice to reduce code by using lambdas:
For even:
return Arrays.stream(array).allMatch( i -> i % 2 == 0);
for odd:
return Arrays.stream(array).allMatch( i -> i % 2 == 1);
Just check for an odd element, if not present then all are even.
public boolean isEvens (int[] array){
for (int i = 0; i < array.length; i++) {
if (array[i] % 2 != 0) {
return false;
}
}
return true;
}
You want to be comparing array elements at index i, and not i itself.
The check should be if (array[i] % 2 == 0)
Use Below code to for reference use a[i]
public static void isEvens() {
int [] array = {1,2,3,4,5};
for (int i = 0; i<array.length;i++) {
if (array[i] % 2 == 0) {
System.out.println("Even");
}
else {
System.out.println("Odd");
}
}
I would recommend using recursion for it, because with recursion the run time will be less than with loops, also it's some lines of code.
I made a code for doing this but with c#, I will post it below, it might help you, because the syntax in java is so similar to the syntax of c#.
public static bool isAllEvens(int[] a, int index)
{
if (index == 0 && a[index] % 2 == 0) return true;
else
{
if (a[index] % 2 == 0)
return true && isAllEvens(a, index - 1);
return false;
}
}
And to call this function just call it with two parameters(array, and array.length - 1 which is the last index).
Here is an example for calling this function:
int[] a = new int[4];
a[0] = 8; a[1] = 4; a[2] = 8; a[3] = 8;
Console.WriteLine(isAllEvens(a, a.Length - 1));
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
My program that calculates the sum of primes is very slow for very large nth term. Please how do I optimize the processing time of my program? The fastest program will be appreciated and the reason why mine is slow for large sets of data. Thanks.
Here's the Java program:
public class SumOfPrimes {
public static void main(String[] args) {
primeNumber(2000000);
}
public static void primeNumber(int nth) {
int counter = 0, i = 2;
while(i>=2) {
if(isPrime(i)) {
counter += i;
}
i++;
if(i == nth) {
break;
}
}
System.out.println(counter);
}
public static boolean isPrime(int n) {
boolean prime = true;
int i;
for(i= 2; i < n; i++) {
if (n % i == 0) {
prime = false;
for (int j = 3; j * j < n; j += 2) {
if (n % j == 0) prime = false;
}
}
}
return prime;
}
}
Well, it's unclear why you have an inner for loop in your isPrime. Removing it will save much time.
Besides, once you find that n is not prime, you should return immediately. Either break out of the loop, or just return false.
Another optimization would be not to test all the number until i < n. It's enough to test until i * i <= n.
public static boolean isPrime(int n) {
int i;
for(i = 2; i * i <= n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
Remember primes you have found, and only test them.
Remove the inner loop.
Test 2, 3, then all odds.
Something like...
public boolean isPrime( ArrayList<Long> primes, long n ){
for( Long t : primes ){
if( n % t == 0 ){
return false;
}
if( t * t > n )return true;
}
return true;
}
public void sumOfPrimes()
{
ArrayList<Long> primes = new ArrayList<Long>();
long n;
double count = 0;
for( n = 2; n < 2000000; n++ ){
if( isPrime( primes, n ) ){
primes.add( n );
count += n;
}
}
}
This should be your isPrime function-
bool isPrime (int number) {
if (number < 2) return false;
if (number == 2) return true;
if (number % 2 == 0) return false;
for (int i=3; (i*i) <= number; i+=2) {
if (number % i == 0 ) return false;
}
return true;
}
Putting together all the answers to my question above, my program has been re-written and it is much faster for very large datasets.
public class SumOfPrimes {
public static void main(String[] args) {
primeNumber(2000000);
}
public static void primeNumber(int nth) {
int i = 2;
long counter = 0;
while(i>=2) {
if(isPrime(i)) {
counter += i;
}
i++;
if(i == nth) {
break;
}
}
System.out.println(counter);
}
public static boolean isPrime (int n) {
if (n < 2) return false;
if (n == 2) return true;
if (n % 2 == 0) return false;
for (int i=3; (i*i) <= n; i+=2) {
if (n % i == 0 ) return false;
}
return true;
}
}
#aega's solution for the isPrime function did the trick. Now 2 million datasets can be calculated for less than 2 secs.
We no need to test from 1 to n, even 3 to n/2 or 3 to sqrt(n) is also too much for testing for a bigger number.
To make the testing the least, we can only test n with the previous prime that have been found up to sqrt(n), like what mksteve has mentioned.
static List<Integer> primes = new ArrayList<>();
static boolean isPrime (int number) {
if (number < 2) return false;
if (number == 2) return true;
if (number % 2 == 0) return false;
int limit = (int) Math.sqrt(number);
for (i : primes) {
if (i > limit) break;
if (number % i == 0 ) return false;
}
return true;
}
public static void primeNumber(int nth) {
int i = 2;
long counter = 0;
while(i <= nth) {
if(isPrime(i)) {
counter += i;
primes.add(i);
}
i++;
}
System.out.println(counter);
}
A faster program will be to store the generated prime numbers in an array and use only those elements for divisibility check. The number of iterations will reduce dramatically. An element of self-learning is there in this.
I don't have time right now. But, when I'm free, will write a java code to implement this.
Use the power of Lambda for dynamic functional referencing and streams for optimized performance with inbuilt filter conditions.
public static boolean isPrime(final int number) {
return IntStream.range(2,(long) Math.ceil(Math.sqrt(number + 1))).noneMatch(x -> number % x == 0);
}
Let's say I have an array and a boolean method. This boolean method will return true if all the positive numbers appear before all the non-positive numbers (0 inclusive). Otherwise, it will return a false value.
The first array newArrayTrue will return a true value because all the positive numbers appear before all the non-positive numbers and 0. Whereas in newArrayFalse, it will return a false value because 0 appear before 5, and 5 is a positive number.
int[] newArrayTrue = {3,1,-4,0,-5};
int[] newArrayFalse = {3,1,-4,0,5};
public static boolean isPositiveFirst(int[] numbers) {
for (int i=0; i<numbers.length; i++) {
for (int j=i+1; i<numbers.length; i++) {
if (numbers[i] > 0 && (numbers[i+1] < 0 || numbers[i+1] == 0)) {
return true;
}
}
}
return false;
}
}
Do I need to have a nested for loop inside the boolean method or it can be done in just one for loop? And I need help with my conditions as I don't really get what's the issue with it. Appreciate any help.
This should suffice:
public static boolean isPositiveFirst(int[] numbers) {
for(int i = 1; i < numbers.length; i++) {
if(numbers[i] > 0 && numbers[i-1] <= 0) {
return false;
}
}
return true;
}
Also some credit to #Ryan, since he deleted his answer on which I based my code.
You can just use a boolean variable encounteredNegative and set it to true if you encounter a 0 or a negative number. Then continue the iteration and if a positive number is found the method should return false. If the loop ends the method returns true.
Something like this:
public static boolean isPositiveFirst(int[] numbers) {
boolean encounteredNegative = false;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] <= 0) {
encounteredNegative = true;
} else {
if (encounteredNegative) {
return false;
}
}
}
return true;
}
How about this.
private static boolean areAllPositiveFirst(int[] a)
{
boolean f=false,ans=true;
for (int i = 0; i < a.length; i++)
{
if(f && a[i]>0)
{
ans=false;
break;
}
if(a[i]<=0)
f=true;
}
return ans;
}
As an alternative to the given answers, using IntStream you can do something like :
public static boolean isPositiveFirst(int[] numbers) {
int k = IntStream.range(0, numbers.length).filter(i -> numbers[i]<1).findFirst().orElse(-1);
if(k < 0)
return true;
else
return IntStream.of(Arrays.copyOfRange(numbers, k, numbers.length)).filter(i-> i>0).count() <1;
}
I see that Lyubomir Papazov already came up with this algorithm. My implementation is just a little more terse:
public static boolean isPositiveFirst(int[] numbers) {
boolean seenNonPositive = false;
for(int i : numbers) {
if(i < 1) seenNonPositive = true;
else if(seenNonPositive) return false;
}
return true;
}
Java newbie here, I'm doing some practice about array on Codingbat haveThree. This is the question :"Given an array of ints, return true if the value 3 appears in the array exactly 3 times, and no 3's are next to each other." My code works on most situation but not all.
My code:
public boolean haveThree(int[] nums){
int counter=0;
for(int i=0; i<nums.length-2;i++){
if(nums[i]==3){
counter++;
}
if(counter==3){
return true;
}
}
return false;
}
Can anyone help me and tell me where I was wrong? How can I fix it?
"Given an array of ints, return true if the value 3 appears in the
array exactly 3 times, and no 3's are next to each other."
you're almost there, however, there are a few mistakes and incomplete implementations:
you didn't check if the value 3 is next to another value 3 (in which case we return false)
you return as soon as count == 3 even though you didn't search the entire array to conclude that there is no more 3s.
as it stands your loop condition i < nums.length-2 doesn't include the last two elements of the array within the search.
solution:
public boolean haveThree(int[] nums){
int counter = 0;
for(int i = 0; i < nums.length; i++){
if(nums[i] == 3){
counter++;
}
if(i + 1 < nums.length) {
if (nums[i] == 3 && nums[i + 1] == 3) return false;
}
}
if(counter == 3) return true;
return false;
}
Here is my solution for this, Have a look :)
public boolean haveThree(int[] nums) {
boolean check=true;
int count = 0;
for(int i=0;i<nums.length;i++){
if( nums[i]==3 && count++>0 && ( (i>0 && nums[i-1] == 3) || (i<nums.length-1 && nums[i+1] == 3) ) )
{//just checking if there are any consecutive 3's next to each other and counting them
check = false;
}
}
return (check && count==3);//count should be 3 and no 3's should be next to each other
}
Here is my solution, which passed all the tests on CodingBat:
public boolean haveThree(int[] nums) {
int counter3 = 0;
if (nums.length >= 5) {
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 3) {
counter3++;
}
}
}
if (counter3 == 3) {
for (int i = 0; i < nums.length - 4; i++) {
if ( (nums[i] == 3) &&
(nums[i+1] != 3) &&
(nums[i+2] == 3) &&
(nums[i+3] != 3) &&
(nums[i+4] == 3)
) { return true; }
}
}
return false;
}
Your loop does not lookup for each element you are missing the last 2 ones. Should be i < nums.length or use simply enhanced for so you don't have to save the current num on a value.
Check if no 3's are next to each other, because now you aren't checking that. I think the best salution to secure that no 3's are next to each other is to save the last number and compare it to the current one.
You can only be sure that the value 3 appears exactly 3 times in the array if you had seen the whole array so check that at the end and not in the loop.
public boolean haveThree(int[] nums) {
int lastNum = 0;
int counter = 0;
for (int currNum : nums) {
if (currNum == 3) {
counter++;
if (lastNum == currNum) {
return false;
}
}
lastNum = currNum;
}
return counter == 3;
}
A very Simple solution for this problem:
public boolean haveThree(int[] nums) {
int count = 0;
int preNum = 0;
for(int i =0; i<nums.length;i++){
if(nums[i]==3){
count++;
if(preNum ==3){
return false;
}
}
preNum = nums[i];
}
return count == 3;
}
I have a Long array with these numbers:
long[] = {1,2,3,5,6,7};
Notice that 4 is missing.
What's the best way to test this array if any such gaps exist or not?
If you're guaranteed that arrays is ordered without any duplicate then you could check that in O(1)
I think this code should work in this specific case :)
//assume that given array is ordered and has no duplicated value
long[] myarray = {5,6,7}; //no gap
long[] myarray1 = {1,2,4}; //has gap
long[] myarray2 = {10,11,12,13,14,15}; //no gap
//return true if has gap
//return false if no gap
//throw null-pointer if empty
public static boolean checkIfHasGap(long[] array) {
if (array.length == 0) {
throw new NullPointerException("Given Array is empty");
} else {
return array[0] + array.length != array[array.length - 1] + 1;
}
}
public static boolean hasGaps(long[] array) {
if (array == null || array.length == 0) {
return false;
}
if (array[array.length - 1] - array[0] + 1 != array.length) {
return true;
}
for (int i = 1; i < array.length; i++) {
if (array[i] != array[i - 1] + 1) {
return true;
}
}
return false;
}
This method first check for the "easy" cases, then iterate the array to check the more complex cases.
Loop through the array and check, if the current item is exactly x more than the current index, where x is the first element in your array.
public boolean hasGaps(long[] array) {
if(array == null || array.length == 0) {
return false;
}
long start = array[0];
for(int i = 0; i < array.length; i++) {
if(array[i] != i + start) {
return true;
}
}
return false;
}
A simpler and reliable way:
const getMissingNumbers = (list) => {
if (!list || list.length === 0) return [];
const missing = [];
// sort the list
list.sort((a, b) => a - b);
// pin start and end points in the list
const step = list[0];
const last = list[list.length - 1];
for (let i = step; i < last; i++) {
if (list.indexOf(i) === -1) missing.push(i);
}
return missing;
}
This the question I must answer-
Given an array of ints, return true if the value 3 appears in the array exactly 3 times, and no 3's are next to each other.
haveThree({3, 1, 3, 1, 3}) → true
haveThree({3, 1, 3, 3}) → false
haveThree({3, 4, 3, 3, 4}) → false
This is my solution:
public boolean haveThree(int[] nums) {
int count = 0;
for (int i=0;i<nums.length-1;i++) {
if (nums[i] == 3 && nums[i+1] ==3) {
return false;
}
else
if ((nums[i]==3 && nums[i+1]!=3)||(nums[i]==3 && nums[i+1]!=3)) {
count ++;
}
}
return count ==3;
}
It fails for some tests. For example {3,1,3,1,3} should result in true being returned; however, false is returned and I can't figure out why.
You need to loop all the way to nums.length to count all occurences. Also, there is no need for the else statement. I would do something like:
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 3) {
if ((i < nums.length - 1) && (nums[i + 1] == 3)) {
return false;
}
count++;
}
}
It fails for that example because you don't check the last index, presumably to fix the out of bounds error for checking if two 3's are next to eachother. Also the or condition in your second if statement is redundant.
public boolean haveThree(int[] nums) {
int count = 0;
for (int i=0;i<nums.length-1;i++) {
if (nums[i] == 3 && nums[i+1] ==3) {
return false;
}
if ((nums[i]==3)) { //removed redundant condition and doesn't need to be an else
count ++;
}
}
// check the last index, you've already ensured the second to last is not also a 3
if(nums[nums.length-1] == 3) {
count++;
}
return count == 3;
}
Because you're not comparing the final value, you can't tell if the last array element is a three or not. What I would do (to guarantee going through each element as needed) is add a flag boolean that lets you know if the previous value was a three or not (resetting it back to false if the current value is not three).
My example:
public boolean haveThree(int[] nums) {
int count = 0;
boolean flag = false;
for(int i = 0; i < nums.length; i++) {
if(nums[i] == 3) { // The current value is a 3
if(flag) { // Previous value was a 3, rejecting.
return false;
}
else { // We have another 3, set the flag
count++;
flag = true;
}
}
else { // Since this wasn't a 3, we can set the flag back to false
flag = false;
}
}
return count == 3;
}
The for statement also has another form designed for iteration through Collections and arrays, and can be used to make your loops more compact and easy to read.
boolean haveThree(int[] nums) {
int count = 0, prevNum = 0;
for (int i : nums){
if (i==3) {
count++;
if (prevNum == i)
return false;
}
prevNum = i;
}
return count == 3;
}
As some people have already pointed out, you are not counting all the 3s that are present in the array. Your loop ends just before the last element in order to avoid ArrayIndexOutOfBoundsException.
It is a logical error. Your code fails for the test case that you've mentioned because first if condition returns false when i = 0. I wrote the following code snippet when I practiced. Hope it helps.
public boolean haveThree(int[] nums) {
int threeCount = 0;
boolean successive3s = false;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 3) {
threeCount++;
}
if (nums[i] == 3 && (i + 1) < nums.length && nums[i + 1] == 3)
successive3s = true;
}
return (!successive3s && threeCount == 3);
}
public boolean haveThree(int[] nums) {
int count = 0;
if(nums.length >= 1 && nums[0] == 3)
count++;
for(int i = 1; i < nums.length; i++) {
if(nums[i - 1] == 3 && nums[i] == 3)
return false;
if(nums[i] == 3)
count++;
}
return count == 3;
}
I made a trailing counter for mine.
public boolean haveThree(int[] nums)
{
//We check to see if it is possible to get 3 without being in a row.
//In this case, it is the smallest at five chars
//E.G 31313, so if we have any size less than this, we know it to be false.
if (nums.length >= 5)
{
//Create a counter to track how many 3's we have in a row,
//as well as how many we have total.
int counterInRow = 0;
int counterThrees = 0;
//Check for 3's
for (int i = 0; i < nums.length; i++)
{
//If a number is 3, we increment both;
if (nums[i] == 3)
{
counterInRow++;
counterThrees++;
}
//Otherwise, we reset the amount in a row to 0;
else
{
counterInRow = 0;
}
//If we have 2 or more in a row, we return false.
if (counterInRow >= 2)
{
return false;
}
}
//Return if the amount of the counterThrees equals 3 or not.
return (counterThrees == 3);
}
//If we have less than 5 characters, it isn't possible. We then,
//Return false;
else
{
return false;
}
}