The Array-2 section of CodingBat present 30 problems of varying difficulty. Most you should be able to solve straight away, while a few may take you up to half an hour or so.

All solutions were successfully tested on 3 March 2013.

**countEvens:**

public int countEvens(int[] nums) { int count = 0; for (int i = 0; i < nums.length; i++) if (nums[i] % 2 == 0) count++; return count; }

**bigDiff:**

public int bigDiff(int[] nums) { int max = nums[0]; int min = nums[0]; for (int i = 0; i < nums.length; i++) { if (nums[i] > max) max = nums[i]; if (nums[i] <= min) min = nums[i]; } return max - min; }

It wasn’t clear to me why the instructions mentioned the inbuilt Math.min(int a, int b) and Math.max(int a, int b) functions. If you use those, you’ll only end up with a more complicated method.

A common mistake people make in this kind of exercise is to initialize the maximum or minimum value with 0 and a very large number, respectively, instead of using an actual value from the array. Given the test cases on CodingBat, you would get away with, for instance, initializing “max” with 0 and “min” with 1000, but if the array you process only consists of numbers that are either all smaller than “max” or all larger than “min”, you’d get the wrong result.

**centeredAverage:**

public int centeredAverage(int[] nums) { int max = nums[0]; int min = nums[0]; int sum = 0; for (int i = 0; i < nums.length; i++) { sum += nums[i]; if (nums[i] > max) max = nums[i]; if (nums[i] < min) min = nums[i]; } return (sum - (max + min)) / (nums.length - 2); }

**sum13:**

public int sum13(int[] nums) { int total = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] != 13) total += nums[i]; else if (i <= nums.length - 1) i++; } return total; }

**sum67:**

public int sum67(int[] nums) { int sum = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] != 6) sum += nums[i]; else while (nums[i] != 7) i++; } return sum; }

**has22:**

public boolean has22(int[] nums) { for (int i = 0; i <= nums.length - 2; i++) if (nums[i] == 2 && nums[i + 1] == 2) return true; return false; }

**lucky13:**

public boolean lucky13(int[] nums) { for (int i = 0; i < nums.length; i++) if (nums[i] == 1 || nums[i] == 3) return false; return true; }

**sum28:**

public boolean sum28(int[] nums) { int sum = 0; for (int i = 0; i < nums.length; i++) if (nums[i] == 2) sum += 2; return sum == 8; }

**more14:**

public boolean more14(int[] nums) { int ones = 0; int fours = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] == 1) ones++; if (nums[i] == 4) fours++; } return ones > fours; }

**only14:**

public boolean only14(int[] nums) { for (int i = 0; i < nums.length; i++) if (nums[i] != 1 && nums[i] != 4) return false; return true; }

JericoMy solution for the bigDiff using the inbuilt Math.min(int a, int b) and Math.max(int a, int b) functions is:

public int bigDiff(int[] nums) {

int large = 0;

int small = nums[0];

for(int i = 0; i < nums.length; i++){

large = Math.max(large, nums[i]);

small = Math.min(small, nums[i]);

}

return large – small;

}

Gregor UlmPost authorThanks. As I pointed out in the article, the problem with using the inbuilt functions min and max is that you’ll end up with a more complicated function. Of course, the number of lines of codes is the same, but you’ll have significantly more overhead due to the calls to Math.max and Math.min.

By the way, it’s a (common) mistake to initialize the variable ‘large’ as 0. What would happen if you were processing an array that only consisted of negative numbers?

onzGregor,

You make a good point about Jerico’s solution starting at zero,

but the amount of overhead in making the inline calls is small.

Calling the min and max functions make the code less bug-prone due to omission of if statements. For beginning programmers, this is key.

Gregor UlmPost authorFirst, in his code he makes calls to both functions with every step of the iteration. Sure, it’s still in O(n), and we can now wax lyrical about constant factors not mattering, at least in theory, but it’s a less efficient solution. Just imagine you had to process an array of billions of items! Further, if someone can’t wrap his head around conditional statements, then maybe computing isn’t a suitable field for them.

JYJFor sum67 code, why doesn’t the code work if I erase “else?” I thought else was always omittable.

Gregor UlmPost authorThe else-clause in an if/else statement is certainly not something you can always omit. If it was, most imperative languages arguably wouldn’t have that construct. Thus, you were either taught by an incompetent, or misunderstood something.

BMANHi, just wanted to say I appreciate for sharing your solutions. I really enjoy after solving some of the exercises to see how others how solved them and see the differences. I have also a few times where I couldn’t get my head around some of the looked at your solutions and find myself stupid for not realizing how easy it was. Thanks 🙂

Gregor UlmPost authorYes, when you can just look up the solution, everything is easy.

LionBoyI duplicate BMAN’s words. You are truly amazing Gregor Ulm. Thank you for sharing!

Gregor UlmPost authorYou’re welcome.

ThatGuy!When is it good practice to use the ternary conditional operator and when is it not?

I can do things like this:

public String fizzString(String str) {

return str.substring(0,1).equals(“f”)&&str.substring(str.length()-1,str.length()).equals(“b”) ? “FizzBuzz”: str.substring(0,1).equals(“f”)?”Fizz”:str.substring(str.length()-1,str.length()).equals(“b”)?”Buzz”:str;

}

and this

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

return a+b==c?true:a+c==b?true:b+c==a?true:false;

}

but these doesnt seem very readable…

Gregor UlmPost authorThe ternary operator makes sense for simple conditional statements as it leads to more concise and still very readable code. On the other hand, as you’ve noticed, it makes nested conditional statements hard to read.

ThatGuy!Ok, thanks 🙂

Jinwoo HwangThank you for your codes, Gregor.^^

By the way, for the code for sum13, I think there should be

num[i+1}!=13

in the else if statement.

if not, for this input {1,2,3,4,13,13,4,5}, we get 19 instead of 15.

Thanks.

WillHeres mine…bigDiff is asking to be sorted.

public int bigDiff(int[] nums) {

Arrays.sort(nums); //now the array has smalelst to biggest values

return(nums[nums.length – 1] – nums[0]);

}

Gregor UlmPost authorYou’re not supposed to use the inbuilt sorting method here as it defeats the purpose of the exercise. The CodingBat exercises are intended to help you develop basic programming skills, which, sadly, even a lot of students in computer science or software engineering lack. If you think you’re too ‘smart’ to solve those rather simple exercises on your own, instead of abusing the Java standard library — sorting an array in this example is ludicrous — you’re only going to get incredibly frustrated once you move beyond basic programming exercises.

Christopher ButtonMy own attempt is rather appallingly verbose, but I managed it and also did it without calling the Math functions. I used a bubble sort instead, and simply subtracted the last (greatest) value in the array from the first:

public int bigDiff(int[] nums) {

boolean flag = true;

while (flag) {

flag = false;

for (int i = 0; i < nums.length; i++) {

if (i + 1 nums[i + 1]) {

//bubble sort

int tmp = nums[i];

nums[i] = nums[i + 1];

nums[i + 1] = tmp;

flag = true;

}

}

}

}

int result = nums[nums.length – 1] – nums[0];

return result;

}