CodingBat Flashcards

1
Q

We want to make a row of bricks that is goal inches long. We have a number of small bricks (1 inch each) and big bricks (5 inches each). Return true if it is possible to make the goal by choosing from the given bricks.

A
public boolean makeBricks(int small, int big, int goal) {
 int x = Math.min(big,goal/5);
 goal -= 5*x;
 if(goal<=small) return true;
 else return false;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

We want make a package of goal kilos of chocolate. We have small bars (1 kilo each) and big bars (5 kilos each). Return the number of small bars to use, assuming we always use big bars before small bars. Return -1 if it can’t be done.

A
public int makeChocolate(int small, int big, int goal) {
  while (big >0 && goal>=5){
    big--;
    goal -=5;
  }
  if(goal<=small)return goal;
  else return -1;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Given an array of ints, return a new array length 2 containing the first and last elements from the original array. The original array will be length 1 or more.

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

String container = “18 - 86 - 5 - 23 - 125 -“;

A

System.out.println(container.substring(0, container.length() - 3));

How well did you know this?
1
Not at all
2
3
4
5
Perfectly