The Java Learning Project

I started learning Java programming and found a perfect website for practicing: Codingbat.com. CodingBat is a free site of live coding problems to build coding skill in Java and Python. CodingBat is a project by Nick Parlante, a computer science lecturer at Stanford.

I will upload my solutions here.

Given an array of ints of odd length, look at the first, last, and middle values in the array and return the largest. The array length will be a least 1.

maxTriple([1, 2, 3]) → 3
maxTriple([1, 5, 3]) → 5
maxTriple([5, 2, 3]) → 5

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public int maxTriple(int[] nums) {
  int max=0;
  int first=nums[0];
  int last=nums[nums.length-1];
  int mid=nums[nums.length/2];
  if ((first>last) && (first>mid)){
    max=first;
  }else if ((last>first) && (last>mid)) {
    max=last;
  }else{
    max=mid;
  }
  return max;
}

Given an array of ints of odd length, return a new array length 3 containing the elements from the middle of the array. The array length will be at least 3.

midThree([1, 2, 3, 4, 5]) → [2, 3, 4]
midThree([8, 6, 7, 5, 3, 0, 9]) → [7, 5, 3]
midThree([1, 2, 3]) → [1, 2, 3]

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public int[] midThree(int[] nums) {
  int[] result = new int[3];
  if (nums.length>3){
     result[0]=nums[(nums.length/2)-1];
     result[1]=nums[(nums.length/2)];
     result[2]=nums[(nums.length/2)+1];
  }else{
    result=nums;
  }return result;
}

Start with 2 int arrays, a and b, each length 2. Consider the sum of the values in each array. Return the array which has the largest sum. In event of a tie, return a.

biggerTwo([1, 2], [3, 4]) → [3, 4]
biggerTwo([3, 4], [1, 2]) → [3, 4]
biggerTwo([1, 1], [1, 2]) → [1, 2]

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public int[] biggerTwo(int[] a, int[] b) {
  int sum_a;
  int sum_b;
  sum_a=a[0]+a[1];
  sum_b=b[0]+b[1];
  if (sum_a>=sum_b){
    return a;
  }else{
    return b;
  }
}

Keresés

Ajánló