Skip to content

Instantly share code, notes, and snippets.

@bijay-shrestha
Created July 7, 2021 15:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bijay-shrestha/28be3a1b5c4b169d9536067665e9b3e1 to your computer and use it in GitHub Desktop.
Save bijay-shrestha/28be3a1b5c4b169d9536067665e9b3e1 to your computer and use it in GitHub Desktop.
/**
* * An array is defined to be odd-heavy if it contains at least one odd element and every odd
* * element is greater than every even element. So {11, 4, 9, 2, 8} is odd-heavy because the two odd elements (11 and 9)
* * are greater than all the even elements.
* *
* * And {11, 4, 9, 2, 3, 10} is not odd-heavy because the even element
* * 10 is greater than the odd element 9. Write a function called isOddHeavy that accepts an integer array and
* * returns 1 if the array is odd-heavy; otherwise it returns 0.
* *
* * Some other examples: {1} is odd-heavy, {2} is not
* * odd-heavy, {1, 1, 1, 1} is odd-heavy, {2, 4, 6, 8, 11} is odd-heavy, {-2, -4, -6, -8, -11} is not odd-heavy.
* *
* * If you are programming in Java or C#, the function signature is
* * int isOddHeavy(int[ ] a)
*/
package com.basic.practice;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class OddHeavy {
public static void main(String[] args) {
// int[] arrayOfNumbers = {11, 4, 9, 2, 8};
// int[] arrayOfNumbers = {11, 4, 9, 2, 3, 10};
// int[] arrayOfNumbers = {1};
// int[] arrayOfNumbers = {2};
// int[] arrayOfNumbers = {1, 1, 1, 1};
// int[] arrayOfNumbers = {2, 4, 6, 8, 11};
int[] arrayOfNumbers = {-2, -4, -6, -8, -11};
log.info("Checking if the array {} is Odd-heavy. Return 1 for Yes and 0 for No.", arrayOfNumbers);
log.info("Actual Result: {}", isOddHeavy(arrayOfNumbers));
}
static int isOddHeavy(int[] a) {
boolean hasOdd = false;
for (int i = 0; i < a.length; i++) {
if (a[i] % 2 == 1) {
hasOdd = true;
for (int j = 0; j < a.length; j++) {
if (a[j] % 2 == 0) {
if (a[i] < a[j]) {
return 0;
}
}
}
}
}
return hasOdd ? 1 : 0;
}
}
@sanjmgr
Copy link

sanjmgr commented Aug 13, 2022

I believe that hasOdd is unnecessary.

public int isOddHeavy(int[] a) {
    for (int i = 0; i < a.length; i++) {
        int number = a[i];
        if (number % 2 == 1) {
            for (int j = 0; j < a.length; j++) {
                if (a[j] % 2 == 0 && a[i] < a[j]) return 0;
            }
        }
    }

    return 1;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment