The Array-1 section of CodingBat contains 27 basic array exercises, most of which are very simple. In the following three posts I’ll present my solutions. Just like it was the case with the String-1 section, there isn’t much to comment on.

All solutions were successfully tested on 27 January 2013.

**firstLast6:**

public boolean firstLast6(int[] nums) { return nums[0] == 6 || nums[nums.length - 1] == 6; }

**sameFirstLast:**

public boolean sameFirstLast(int[] nums) { return nums.length >= 1 && nums[0] == nums[nums.length - 1]; }

**makePi:**

public int[] makePi() { int[] pie = { 3, 1, 4 }; return pie; }

**commonEnd:**

public boolean commonEnd(int[] a, int[] b) { return a[0] == b[0] || a[a.length - 1] == b[b.length - 1]; }

**sum3:**

public int sum3(int[] nums) { return nums[0] + nums[1] + nums[2]; }

**rotateLeft3:**

public int[] rotateLeft3(int[] nums) { int[] rLeft = { nums[1], nums[2], nums[0] }; return rLeft; }

**reverse3:**

public int[] reverse3(int[] nums) { int[] newOrder = { nums[2], nums[1], nums[0] }; return newOrder; }

**maxEnd3:**

public int[] maxEnd3(int[] nums) { if (nums[2] > nums[0]) { nums[0] = nums[2]; nums[1] = nums[2]; } else { nums[1] = nums[0]; nums[2] = nums[0]; } return nums; }

**sum2:**

public int sum2(int[] nums) { if (nums.length == 0) return 0; if (nums.length == 1) return nums[0]; return nums[0] + nums[1]; }

**middleWay:**

public int[] middleWay(int[] a, int[] b) { int[] c = { a[1], b[1] }; return c; }

mayhsThis should also work perfectly fine:

int maxi= Math.max(nums[0],nums[2]);

nums[0]=maxi;nums[1]=maxi;nums[2]=maxi;

return nums;

mayhsmiddleWay:

int na[]=new int[2];

na[0]=a[1];

na[1]=b[1];

return na;

Gregor UlmPost authorThis does work, too, but what’s the point of your much more verbose code? I don’t see why you wouldn’t want to initialize the array with the correct values, which is what I’ve done in my solution above.

Frank ShepherdWhat does int mean?

Gregor UlmPost author“int” is one of the primitive data types in the Java. It stands for “integer”, and the range of an “int” is [-2^31, (2^31) – 1].

John DoeI feel a little dumb right now.

In the first exercise why does it need to be:

nums[nums.length-1]

why not just:

nums.length-1

John DoeOk i just realized.

I am an idiot

john doeyeah you are an idiot