CodingBat: Java. Logic-2


For further help with Coding Bat (Java), please check out my books. I am also available for tutoring.


The Logic-2 section of CodingBat contains just nine exercises. Yet, there are slightly more challenging than any of the pervious exercises, which means that you may have to spend more time on them, compared to, say, String-1. “makeBricks” is a favorite of mine, not just because some of the solutions floating around on the Internet are nothing but comical. It’s a similar story with “makeChocolate”.

All solutions were successfully tested on 10 February 2013.

makeBricks:

public boolean makeBricks(int small, int big, int goal) {
	return goal - big * 5 <= small
			&& goal % 5 <= small;
}

I split the line to make the expression more readable.

loneSum:

public int loneSum(int a, int b, int c) {
	if (a == b && b == c) return 0;
	if (a == b) return c;
	if (a == c) return b;
	if (b == c) return a;
	return a + b + c;
}

luckySum:

public int luckySum(int a, int b, int c) {
	if (a == 13) return 0;
	if (b == 13) return a;
	if (c == 13) return a + b;
	return a + b + c;
}

noTeenSum:

public int noTeenSum(int a, int b, int c) {
	return fixTeen(a) + fixTeen(b) + fixTeen(c);
}

public int fixTeen(int n) {
	return (n >= 13 && n < 15 || n > 16 && n <= 19) ? 0 : n;
}

roundSum:

public int roundSum(int a, int b, int c) {
	return round10(a) + round10(b) + round10(c);
}

public int round10(int num) {
	return (num % 10 < 5) ? (num / 10 * 10) : (num / 10 * 10 + 10);
}

closeFar:

public boolean closeFar(int a, int b, int c) {
	if (Math.abs(b - c) < 2) return false;
	return Math.abs(a - b) <= 1 && Math.abs(a - c) >= 2
			|| Math.abs(a - c) <= 1 && Math.abs(a - b) >= 2;
}

blackjack:

public int blackjack(int a, int b) {
	if (a > 21 && b > 21) return 0;
	if (a > 21 && b <= 21) return b;
	if (a <= 21 && b > 21) return a;
	return Math.max(a, b);
}

evenlySpaced:

public boolean evenlySpaced(int a, int b, int c) {
	int min = Math.min(Math.min(a, b), c);
	int mid = Math.max(Math.min(a, b), c);
	int mid2 = Math.min(Math.max(a, b), c);
	int max = Math.max(Math.max(a, b), c);
	return Math.abs(mid - min) == Math.abs(mid - max)
			|| Math.abs(mid2 - min) == Math.abs(mid2 - max); 
}

makeChocolate:

public int makeChocolate(int small, int big, int goal) {
	int maxBig = goal / 5;
	if (big > maxBig)
		return (goal <= 5 * maxBig + small) ? (goal - 5 * maxBig) : -1;
	return (goal <= 5 * big + small) ? (goal - 5 * big) : -1;
}

The parentheses in the return statements are not necessary, but they allow you to parse the statements more quickly since you can immediately identify all parts of the ternary operator.


For further help with Coding Bat (Java), please check out my books. I am also available for tutoring.


28 thoughts on “CodingBat: Java. Logic-2

  1. Grethe

    For evenlySpaced we’ve also developed some nice solution:


    public boolean evenlySpaced(int a, int b, int c) {
    int [] array = {a, b, c};
    Arrays.sort(array);
    return Math.abs(array[0] - array[1]) == Math.abs(array[2] - array[1]);
    }

    Reply
    1. Gregor Ulm Post author

      Thanks for the comment! Your solution is clear and straight-forward. However, you make use of an in-built sort method, which is something I have avoided with my solutions to the Coding Bat exercises. Of course, in the real world you’d make use of library functions whenever possible and feasible, but for the purposes of Coding Bat this might be counterproductive.

      Reply
      1. Dave

        When I first solved “evenlySpaced” I used ternary statements because I also like to avoid using built-in methods. However, when that becomes tedious I’ll use built-ins like abs, min and, max of the Math class. To that point though, is there really any difference in using a Math class built-in or Arrays class built-in?

        public boolean evenlySpaced(int a, int b, int c) {
        int min = a<b ? (a<c ? a : c) : (bb ? (a>c ? a : c) : (b>c ? b : c); // OR int max = Math.max(a,(Math.max(b,c)));
        int mid = (a+b+c) – d-f;
        return mid – min == max – mid;
        }

        Reply
        1. Dave

          Looking at my last post, something weird must have happened.

          public boolean evenlySpaced(int a, int b, int c) {
          int min = a<b ? (a<c ? a : c) : (bb ? (a>c ? a : c) : (b>c ? b : c);
          int mid = (a+b+c) – min-max;
          return mid – min == max – mid;
          }
          alternatively :
          int min = Math.min(a,(Math.min(b,c)));
          int max = Math.max(a,(Math.max(b,c)));

          Reply
        2. Gregor Ulm Post author

          The cleanest way to solve ‘evenlySpaced’ is by sorting the array first. If you don’t do that, the resulting code is a bit messy. Thankfully, almost all other Coding Bat exercises can be solved in a rather clean and straightforward way.

          Regarding your solution with nested ternary operators: I hold the opinion that nested ternary operators make code quite unreadable and difficult to maintain, which is a good reason for avoiding them. My personal preference is to only replace single if/else statements with the ternary operator.

          Your alternative solution with Math.min and Math.max is my favorite one.

          Reply
      2. Kasper

        The problem is finding the middle number – which is actually easy:
        public boolean evenlySpaced(int a, int b, int c) {
        int x = Math.min(a, Math.min(b, c));
        int y = Math.max(a, Math.max(b, c));
        int z = a+b+c-x-y;
        return (z-x) == (y-z);
        }

        Reply
          1. ginger

            replace “max” and “min” with “Math.max” and “Math.min” in my previous comment, I got a little ahead of myself and didn’t proof read before posting 😮

    2. Dave

      The sort method returns an array sorted into ascending order so you already know array[1] is greater than array[0] and so on.
      You could just use; return array[1] – array[0] == array[2] – array[1];
      No need for Math.abs().

      Reply
    3. wichael mew

      I think I have the simplest solution to evenlySpaced.
      public boolean evenlySpaced(int a, int b, int c) {
      int lol = a+b+c;
      return (lol==3*b || lol==3*a || lol==3*c);
      }

      Reply
      1. Nick

        Nice solution. It inspired me to make this one-liner:

        public boolean evenlySpaced(int a, int b, int c) {
        return Arrays.asList(3*a, 3*b, 3*c).contains(a+b+c);
        }

        Reply
  2. James

    I know it probably wouldn’t make too much sense, but could the makeBricks problem be approached recursively?

    Reply
    1. Gregor Ulm Post author

      Yes, of course. It wouldn’t look like a typical textbook example of recursion, though.

      Reply
  3. Matt G

    I used this one for evenlySpaced :
    public boolean evenlySpaced(int a, int b, int c) {
    return ((a+b+c)/3==a || (a+b+c)/3==b || (a+b+c)/3==c) && (a+b+c)%3==0;

    }

    Let’s say :
    a is the lowest
    b is the middle
    c is the greatest

    We have a+x = b and b+x = c.
    a+b+c = a+a+x+b+x = a+a+x+a+x+x
    a+b+c = 3(a+x)
    a+b+c = 3b
    So (a+b+c)/3 = b AND a+b+c%3=0

    The other ones can be easily deducted when assuming acb, bac, bca, cab and cba orders.

    Reply
  4. Kushagra

    public boolean evenlySpaced(int a, int b, int c) {
    int min = Math.min(Math.min(a, b), c);
    int max = Math.max(Math.max(a, b), c);
    int mid=b; //Assume

    if(amin) mid=a;
    if(bmin) mid=b;
    if(cmin) mid=c;

    return (Math.abs(min-mid)==Math.abs(max-mid));
    }

    Reply
  5. DanChap

    public boolean evenlySpaced(int a, int b, int c) {
    if (a < b && b b && b > c)
    return Math.abs(a – b) == Math.abs(b – c);
    else return Math.abs(a – b) * 2 == Math.abs(b – c)
    || Math.abs(a – b) == Math.abs(b – c) * 2;
    }

    Reply
  6. DanChap

    public boolean evenlySpaced(int a, int b, int c) {
    if (a < b && b b && b > c)
    return Math.abs(a-b) == Math.abs(b-c);

    else return Math.abs(a-b)*2 == Math.abs(b-c)
    || Math.abs(a-b) == Math.abs(b-c)*2;
    }

    Reply
  7. waz

    sorry I’m new to programming. please don’t slay me. at this point, all was trying to do was get it to work. This is posted just for laughs.. finding that middle number really had me going, lol. I decided to put all three numbers into a array and use a for loop to find the middle number. After looking at some of the examples, boy… my mind must have been somewhere else. but hey! it works. You live you learn, lol.
    I really like KASPER’s method of finding the middle number.

    public boolean evenlySpaced(int a, int b, int c) {
    int max = Math.max(Math.max(b,c),a);
    int min = Math.min(Math.min(b,c),a);
    int middle=0;
    int mid[] = {a,b,c};
    for (int i=0; i min && mid[i] < max) middle = mid[i];
    }
    if (max – middle == middle – min) return true;
    if (a == b && b == c) return true;
    return false;
    }

    Reply
  8. waz

    public boolean evenlySpaced(int a, int b, int c) {
    int max = Math.max(Math.max(b,c),a);
    int min = Math.min(Math.min(b,c),a);
    int middle=0;
    int mid[] = {a,b,c};
    for (int i=0; i min && mid[i] < max) middle = mid[i];
    }
    if (max – middle == middle – min) return true;
    if (a == b && b == c) return true;
    return false;
    }

    Reply
    1. waz

      Sorry, my posts are getting messed up from trying to copy and paste it. sorry again.
      public boolean evenlySpaced(int a, int b, int c) {
      int max = Math.max(Math.max(b,c),a);
      int min = Math.min(Math.min(b,c),a);
      int middle=0;
      int mid[] = {a,b,c};
      for (int i=0; i min && mid[i] < max) middle = mid[i];
      }
      if (max – middle == middle – min) return true;
      if (a == b && b == c) return true;
      return false;
      }

      Reply
  9. Timothy Crittenden

    This to me seems a nice clean way of doing evenlySpaced. Only been doing this while, perhaps someone will tell me otherwise.

    public boolean evenlySpaced(int a, int b, int c) {

    if (a – b == b – c) {
    return true;
    }
    if (b – a == a – c) {
    return true;
    }
    if (b – c == c – a) {
    return true;
    }
    return false;
    }

    Reply
    1. Gregor Ulm Post author

      That’s quite nice. You could even contract it further to “return (a – b == b – c) || … || …”.

      Reply
  10. Nicolò Polazzi

    My solution for evenlySpaced :
    public boolean evenlySpaced(int a, int b, int c) {
    return (a-b == b-c || b-a == a-c || a-c == c-b) ? true : false;
    }

    Reply
  11. Shekhar

    My solutiion for makeChocolate.

    public int makeChocolate(int small, int big, int goal) {

    int mult = goal/5;

    if (mult > big){
    return (goal – big*5 > small)? -1 : (goal – big*5);
    }
    else{
    return (goal – 5*mult > small)? -1 : (goal – 5*mult);
    }
    }

    Reply
  12. Nick

    A one-liner for makeChocolate:

    public int makeChocolate(int small, int big, int goal) {
    return (goal -= 5 * Math.min(goal / 5, big)) <= small ? goal : -1;
    }

    Reply
  13. Alan

    My Rust based solution for evenlySpaced:

    use std::cmp;
    fn evenlySpaced(a: i32, b: i32, c: i32) -> bool {
    let max = cmp::max(a, cmp::max(b, c)) as f32;
    let min = cmp::min(a, cmp::min(b, c)) as f32;
    let x: Vec = vec![a as f32, b as f32 , c as f32];
    return x.contains(&((min + max) / 2.0))
    }

    fn main() {
    let evenlySpaced_tests = vec![
    (2, 4, 6),
    (4, 6, 2),
    (4, 6, 3),
    (6, 2, 4),
    (6, 2, 8),
    (2, 2, 2),
    (2, 2, 3),
    (9, 10, 11),
    (10, 9, 11),
    (10, 9, 9),
    (2, 4, 4),
    (2, 2, 4),
    (3, 6, 12),
    (12, 3, 6)];
    for i in evenlySpaced_tests {
    println!(“evenlySpaced: {:?} -> {}”, i, evenlySpaced(i.0 , i.1, i.2))
    }
    }

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Spammer prevention; the answer is an integer: * Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.