CodingBat: Java. Array-1, Part II


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


makeEnds:

public int[] makeEnds(int[] nums) {
	int[] result = { nums[0], nums[nums.length - 1] };
	return result;
}

has23:

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

no23:

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

This is one of the examples where I wonder why Nick Parlante even bothered with the exercise, since it is analog to the previous one and therefore feels like busywork.

makeLast:

public int[] makeLast(int[] nums) {
	int[] result = new int[2 * nums.length];
	result[result.length - 1] = nums[nums.length - 1];
	return result;
}

double23:

public boolean double23(int[] nums) {
	int twoCount = 0;
	int threeCount = 0;
	for (int i = 0; i < nums.length; i++) {
		if (nums[i] == 2)
			twoCount++;
		if (nums[i] == 3)
			threeCount++;
	}
	return twoCount == 2 || threeCount == 2;
}

fix23:

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

start1:

public int start1(int[] a, int[] b) {
	int count = 0;
	if (a.length > 0 && a[0] == 1)
		count++;
	if (b.length > 0 && b[0] == 1)
		count++;
	return count;
}

biggerTwo:

public int[] biggerTwo(int[] a, int[] b) {
	if (a[0] + a[1] < b[0] + b[1])
		return b;
	return a;
}

makeMiddle:

public int[] makeMiddle(int[] nums) {
	int[] result = { nums[nums.length / 2 - 1], nums[nums.length / 2] };
	return result;
}

plusTwo:

public int[] plusTwo(int[] a, int[] b) {
	int[] result = { a[0], a[1], b[0], b[1] };
	return result;
}

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


4 thoughts on “CodingBat: Java. Array-1, Part II

  1. Armika

    about has23 and no23.
    I think Nick Parlante didnt want to use a loop. These exercises are for the practice with || and &&.
    public boolean has23(int[] nums) {
    return (nums[0]==2 || nums[0]==3 || nums[1]==2 || nums[1]==3);
    }

    public boolean no23(int[] nums) {
    return (nums[0]!=2 && nums[0]!=3 && nums[1]!=2 && nums[1]!=3);
    }

    Reply
  2. taha hashmi

    public boolean double23(int[] nums) {
    return (nums.length>1 && nums[0]==nums[1] && (nums[0]==2 || nums[0]==3));
    }
    works too

    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.