Wednesday, May 6, 2015

Wednesday, May 6th

Regular class today.

I worked on String 2, and managed to get a few problems done. Only 6 problems left after this class !

I worked on a few interesting problems. One problem asked me to return true or false according to what a part of the string was, when there was a star. What they asked of me, I could do. The problem for me came when there were multiple stars, and I had already returned true, when the next star appearance turned out to be false. I could only return true if their conditions applied to all of the stars in the string, so how could I write the code so that it would take into consideration all of the other stars in the string?

This is the problem:
----------------------------------------------------------------------------------------------------------------------------------

Returns true if for every '*' (star) in the string, if there are chars both immediately before and after the star, they are the same. 

sameStarChar("xy*yzz") → true
sameStarChar("xy*zzz") → false
sameStarChar("*xa*az") → true

public boolean sameStarChar(String str) {
  
  if (!str.contains("*")){
   return true;
  }
// if the string doesn't even contain a star, then return true since we won't even have that //problem.
  
  for (int i=1;i<str.length()-1;i++)
  {
  
    if (str.substring(i,i+1).equals("*"))
// we want to make sure we're dealing with a star.
  {
  
      if (!str.substring(i-1,i).equals(str.substring(i+1,i+2)))
  {
         return false;
// if the star's characters before and after are not the same, then return false;
  }
  

  }
  
 }
  
  return true;
// otherwise, return true. The fact that we put the return true at the end, allowed the computer
// to go through the entire string, and if it finds one irregularity with the stars, it will return 
// false. It will only return true if all of the instances of stars have the chars before and after
// the same.

}

------------------------------------------------------------------------------------------------------------

It is thanks to Mr. Daly that I understood this problem. He explained the logic to me when I came to see him. 

I am currently working on another problem with stars, but I haven't completed it. I will most likely show that one for next class's blog. 

Looking forward to finishing Level 2 !

No comments:

Post a Comment