Regular class today. Came in and got straight to work.
Unlike last class, I didn't have a streak of easy problems - in fact, I had a streak of harder problems. CodingBat is like that - sometimes you can have 4 or 5 easy problems, and after that you can have 4 or 5 that are much harder.
I got 2 problems that were quite similar - which required me to check the values of two adjacent numbers. I didn't know how to that at first, so I couldn't solve the problem. Mr. Daly taught me that simply you say the value of [i] and then the value of [i+1]. Like this:
if (nums[i]==2 && nums[i+1]==2)
Here is one of the problems I did today, that included the two adjacent values:
----------------------------------------------------------------------------------------------------------------------------------
Given an array of ints, return true if the array contains a 2 next to a 2 or a 4 next to a 4, but not both.
public boolean either24(int[] nums) {
boolean two = false;
boolean four = false;
// create two boolean values for a 2 next to a 2 and a 4 next to a 4.
for (int i =0;i<nums.length-1;i++)
{
if (nums[i]==2 && nums[i+1]==2)
{
two =true;
// if there is a 2 next to a 2, then the boolean two is true.
}
if (nums[i]==4 && nums[i+1]==4)
{
four =true;
// if there is a 4 next to a 4, then the boolean four is true.
}
}
if (two&&four)
{
return false;
// if there is a 2 next to a 2, and a 4 next to a 4, then that is not allowed so return false.
}
if (two || four)
{
return true;
// if there is one pair of adjacent same numbers, then return true.
}
return false;
// if none of the above conditions are true and there are no adjacent same number pairs, then return false.
}
See you next class!
No comments:
Post a Comment