Social Icons

Showing posts with label Javabat solutions. Show all posts
Showing posts with label Javabat solutions. Show all posts

Monday, July 12, 2010

scores100 : Solutions for Javabat : 29


Question

Given an array of scores, return true if there are scores of 100 next to each other in the array. The array length will be at least 2.

scores100({1, 100, 100}) → true
scores100({1, 100, 99, 100}) → false
scores100({100, 1, 100, 100}) → true

Solution

public boolean scores100(int[] scores) {
  boolean b=false;
  for(int i=0; i<scores.length;i++){
     if(scores[i]==100 && i+1<scores.length && scores[i+1]==100)
     {
        b=true;
        break;
     }
     else
       b=false;
  }
  return b;
}

Friday, July 9, 2010

scoresIncreasing: Solutions for Javabat:27


Question

Given an array of scores, return true if each score is equal or greater than the one before. The array will be length 2 or more.

scoresIncreasing({1, 3, 4}) → true
scoresIncreasing({1, 3, 2}) → false
scoresIncreasing({1, 1, 4}) → true

Solution

public boolean scoresIncreasing(int[] scores) {
  boolean b=false;
  for(int i=1; i<scores.length;i++){
     if(scores[i]>=scores[i-1])
       b=true;
     else{
       b=false;
       break;
     }  
  }
  return b;
}

Monday, June 28, 2010

xyzMiddle : Solutions for Javabat : 27


Given a string, does "xyz" appear in the middle of the string? To define middle, we'll say that the number of chars to the left and right of the "xyz" must differ by at most one. This problem is harder than it looks.

xyzMiddle("AAxyzBB") → true
xyzMiddle("AxyzBB") → true
xyzMiddle("AxyzBBB") → false

Source

Solution.

 

public boolean xyzMiddle(String s) 
{
  int index=0;
  
  for(int i=0;i<s.length();i++)
  {
    index=s.indexOf("xyz",i);
    if(index!=-1)
    {
      
      if(index==0 && Math.abs( index-(s.length()-(index+3)))<=1) 
        return true; 
      else if( Math.abs( index-(s.length()-(index+3)))<=1 && s.charAt(index-1)!='.')
         return true;   
      else   
         i=index+2;
    }
  }
  return false;  
}

Thursday, June 24, 2010

getSandwich: Solutions for Javabat : 26


It’s been sometime since i posted my last javabat solution. Here I am with a new string question. Question is like this.

A sandwich is two pieces of bread with something in between. Return the string that is between the first and last appearance of "bread" in the given string, or return the empty string "" if there are not two pieces of bread.

getSandwich("breadjambread") → "jam"
getSandwich("xxbreadjambreadyy") → "jam"
getSandwich("xxbreadyy") → ""

Source

Solution

public String getSandwich(String str) {
  int firstI = str.indexOf("bread");
  int lastI  = str.lastIndexOf("bread");
  
  if(firstI==lastI || firstI==-1)
    return "";
  else 
    return str.substring(firstI+5, lastI);  
}

Friday, June 11, 2010

sameStarChar: Solutons for Javabat : 25


Question:

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

Source

Solution:

public boolean sameStarChar(String str) {
  int index=0;
  boolean b=false;
  if(str.length()<=1 || str.indexOf("*")==-1 || str.equals("**")) 
     b=true;
    
  for(int i=1; i<str.length()-1;i++){
    index=str.indexOf("*",i);
    if(index!=-1 && index!=str.length()-1 ){
      if( str.charAt(index-1)==str.charAt(index+1) )
        b= true;
      else
        b=false;
    }   
   
  }
  return b;
}

Monday, June 7, 2010

zipZap: Solutions for Javabat :24


Question:

Look for patterns like "zip" and "zap" in the string -- length-3, starting with 'z' and ending with 'p'. Return a string where for all such words, the middle letter is gone, so "zipXzap" yields "zpXzp".

zipZap("zipXzap") → "zpXzp"
zipZap("zopzop") → "zpzp"
zipZap("zzzopzop") → "zzzpzp"

Source

Solution

public String zipZap(String str) {
  String s="";
 
  int index=0 ; 
  
  for(int i=0;i<str.length();i++){
     index=str.indexOf("z",i);
     if(index!=-1 && index<str.length()-2 && str.charAt(index+2)=='p'){
       //we got a z*p , remove the middle letter
       s+=str.substring(i,index+1)+str.charAt(index+2);
       i=index+2;
       continue;
     }
     else
        s+=str.substring(i,i+1);
     
  }
    
  return s;
}

Thursday, June 3, 2010

starOut : Solutions for Javabat :23


Question: (Source)

Return a version of the given string, where for every star (*) in the string the star and the chars immediately to its left and right are gone. So "ab*cd" yields "ad" and "ab**cd" also yields "ad".

starOut("ab*cd") → "ad"
starOut("ab**cd") → "ad"
starOut("sm*eilly") → "silly"

Solution

public String starOut(String str) {
  if(str.indexOf("*")==-1) return str; // no stars :(
  String starOut="";
  for(int i=0 , lastI=0 ; i<str.length() ; i++){
             
      if(str.charAt(i)=='*' | i==str.length()-1){ // got a star
          if(i==0){// * @ the begining
              i=this.getI(i,str); lastI=i+1;
          }
          else if(i==str.length()-1) { 
              if(str.charAt(i)=='*')
                 starOut+=str.substring(lastI,i-1);
              else
                 starOut+=str.substring(lastI);
              }
              else {
                 starOut+=str.substring(lastI,i-1); // pre * part stored
                 i=this.getI(i,str); lastI=i+1;
              }
          }
     }
     return starOut;
                
}
int getI(int i , String str){
    // skips any adjacent *s 
    while(++i < str.length() && str.charAt(i)=='*' );
    return i;
}

Tuesday, May 25, 2010

plusOut : Solutions for Javabat : 22



Given a string and a non-empty word string, return a version of the original String where all chars have been replaced by pluses ("+"), except for appearances of the word string which are preserved unchanged.

plusOut("12xy34", "xy") → "++xy++"
plusOut("12xy34", "1") → "1+++++"
plusOut("12xy34xyabcxy", "xy") → "++xy++xy+++xy"

Source

Solution-

public String plusOut(String s, String word) {
  String end="";
  for(int i=0 ; i<str.length() ;i++){
       
     if(i<= s.length()-word.length() &&
        s.substring(i,i+word.length()).equals(word)){
        end+=word;
        i+= word.length()-1;       
     }
     else
        end+= "+";
  }
  
  return end;
}



 

Wednesday, May 19, 2010

wordEnds : Solutions for Javabat : 21



Given a string and a non-empty word string, return a string made of each char just before and just after every appearance of the word in the string. Ignore cases where there is no char before or after the word, and a char may be included twice if it is between two words.

wordEnds("abcXY123XYijk", "XY") → "c13i"
wordEnds("XY123XY", "XY") → "13"
wordEnds("XY1XY", "XY") → "11"

Source

public String wordEnds(String str, String word) {
   if(str.indexOf(word)==-1 | str.equals(word)) return "";
    
       String ends="";
         for(int i=0  ; i<str.length() ; i++){
              i=str.indexOf(word, i);
              
              if(i==0) {                               // in the begining
                ends+=""+str.charAt(i+word.length());
                i=i+word.length()-1;
              }
              else if(i==str.length()-word.length()){ // in the end
                ends+=""+str.charAt(i-1);
                break;
              }
              else if(i==-1) break; // no more matches
              else{   // in the middle
                ends+=""+str.charAt(i-1)+str.charAt(i+word.length());
                i=i+word.length()-1;
              }
              
         }
        return ends;
}


Monday, May 17, 2010

notReplace : Solutions for Javabat:20



Given a string, return a string where every appearance of the lowercase word "is" has been replaced with "is not". The word "is" should not be immediately preceded or followed by a letter -- so for example the "is" in "this" does not count. (Note: Character.isLetter(char) tests if a char is a letter.)

notReplace("is test") → "is not test"
notReplace("is-is") → "is not-is not"
notReplace("This is right") → "This is not right"

Source

Solution:

public String notReplace(String s) {
      String news="";
      if(s.indexOf("is")==-1) return s;
      for(int i=0 , end=0 ; i<s.length()-1;i++){
         i=s.indexOf("is",i);
         if(i==0){
             if(s.length()==2) news= "is not";
             else if(!Character.isLetter(s.charAt(2)))   {
                news= "is not";
                end=i=2;
             }
         }
         else if(i== s.length()-2){
            if(!Character.isLetter(s.charAt(i-1)))
              news+= s.substring(end,i)+"is not";
            else
              news+= s.substring(end);
         }
         else if(i==-1){// no more 'is' s
            news+= s.substring(end);
            break;
         }
         else{
            if(!Character.isLetter(s.charAt(i-1))&& 
                 !Character.isLetter(s.charAt(i+2)))
            {
               news+= s.substring(end,i)+"is not";
               end=i=i+2;
            }
         }
      }
      return news;
}

Thursday, May 13, 2010

sumNumbers : Solutions for Javabat : 19


Question:

Given a string, return the sum of the numbers appearing in the string, ignoring all other characters. A number is a series of 1 or more digit chars in a row. (Note: Character.isDigit(char) tests if a char is one of the chars '0', '1', .. '9'. Integer.parseInt(string) converts a string to an int.)

sumNumbers("abc123xyz") → 123
sumNumbers("aa11b33") → 44
sumNumbers("7 11") → 18

Source

Solution
For each digit we find using isDigit() on the passed string , we have to check adjacent characters whether they are digits too. isDigit() is a life saver i must confess.

public int sumNumbers(String s) {
   int sum=0;
   String num="";
   
   if(str.length()==0) return 0;
  
   for(int i=0 ; i<s.length(); i++){
     if(Character.isDigit(s.charAt(i) ) ){
        num=""+s.charAt(i);
        i++;
        while(i<s.length() && Character.isDigit(s.charAt(i)) ){
             num+=""+s.charAt(i);    
             i++;        
        }
        sum+=Integer.parseInt(num);
     }
  }  
  return sum;
}


 

Wednesday, May 12, 2010

maxBlock : solutions for Javabat :18



Given a string, return the length of the largest "block" in the string. A block is a run of adjacent chars that are the same.

maxBlock("hoopla") → 2
maxBlock("abbCCCddBBBxx") → 3
maxBlock("") → 0


source

solution:

public int maxBlock(String str) {
  int block =1 , largestBlock=0 ;
  
  if(str.length()==0) return 0;
  
  for(int i=0 ; i<str.length(); i++){
     while(i+1<str.length() && str.charAt(i)==str.charAt(i+1) ){
     
         block++;i++;
             
     }
     
     if(block>largestBlock) largestBlock=block;
     block=1;
  }
  return largestBlock;
}

Saturday, May 8, 2010

mirrorEnds: solutions for Javabat: 17



Given a string, look for a mirror image (backwards) string at both the beginning and end of the given string. In other words, zero or more characters at the very begining of the given string, and at the very end of the string in reverse order (possibly overlapping). For example, the string "abXYZba" has the mirror end "ab".

mirrorEnds("abXYZba") → "ab"
mirrorEnds("abca") → "a"
mirrorEnds("aba") → "aba"

Source

I used separate method for reverse a given string for it can be reused. one can use StringBuffer or StringBuilder too because those classes have reverse method built in.

public String mirrorEnds(String str) {
  
 String mir="";
 if(str.length()<2) return str;
 int k=1;
   while(str.substring(str.length()-k).equals(this.reverse(str.substring(0,k)))){
      mir=str.substring(0, k);
      k++;
      if(k> str.length()) break; 
      // for overlapping is allowed!
   }
        return mir;
 }
 String reverse(String str){
     String rev="";
     int i=str.length();
     while(--i>=0)
        rev+= str.charAt(i)
        
     return rev;
 }
 

Monday, May 3, 2010

sumDigits: Solutions for Javabat:16


Following question belongs to Strings3 category in Javabat.

Given a string, return the sum of the digits 0-9 that appear in the string, ignoring all other characters. Return 0 if there are no digits in the string. (Note: Character.isDigit(char) tests if a char is one of the chars '0', '1', .. '9'. Integer.parseInt(string) converts a string to an int.)

sumDigits("aa1bc2d3") → 6
sumDigits("aa11b33") → 8
sumDigits("Chocolate") → 0

Source

Given hint almost solves the problem. We iterate through the String using a loop and check whether it is a digit by passing it to isDigit method . If it is a character we convert it to a String by adding an empty string , parse it as an int and finally add to the total. total will be returned. We are assured that the method won’t be passed minus values or floating point numbers , simplifies the matter.

public int sumDigits(String str) {
  int sum=0;
  
  for(int i=0; i<str.length(); i++){
     if(Character.isDigit(str.charAt(i))){
       sum+= Integer.parseInt(str.charAt(i)+"");
     }
  }
  
  return sum;
}


 

Friday, April 30, 2010

centeredAverage: Solutions for Javabat:15


This is somewhat “not-easy-as-it-seems” array question. because there are a lot of things which we would not consider at first. Only After a thorough testing we can get the ultimate solution.

Return the "centered" average of an array of ints, which we'll say is the mean average of the values, except not counting the largest and smallest values in the array. Use int division to produce the final average. You may assume that the array is length 3 or more.

centeredAverage({1, 2, 3, 4, 100}) → 3
centeredAverage({1, 1, 5, 5, 10, 8, 7}) → 5
centeredAverage({-10, -4, -2, -4, -2, 0}) → –3

Source

Solution

public int centeredAverage(int[] nums) {
           if(nums.length <3 ) return 0;
           int len=nums.length; 
           int max=Integer.MIN_VALUE ; 
           int min=Integer.MAX_VALUE ; 
           int sum=0 ;  
           int mini=0; // subscript of max ,min
           int maxi=0;
           // get max,min values and their subscripts
           for(int i=0;i<len;i++){
             if(nums[i]>max){
               max=nums[i];
               maxi=i;
             }
             if(nums[i]<min){
               min=nums[i];
               mini=i;
             }
           }// end for
           // compute the average
           for(int j=0 ; j<len; j++){
              if(maxi==mini) {// all the elements are same
                  sum=nums[0];
                  break;
              }
              if(j != maxi && j != mini)
                 sum+=nums[j];
           }// end for
          return sum/(len-2);
}

Tuesday, April 27, 2010

maxMirror: Solutions for Javabat:14


Question:

Say that a "mirror" section in an array is a group of contiguous elements such that somewhere in the array, the same group appears in reverse order. For example, the largest mirror section in {1, 2, 3, 8, 9, 3, 2, 1} is length 3 (the {1, 2, 3} part). Return the size of the largest mirror section found in the given array.

maxMirror({1, 2, 3, 8, 9, 3, 2, 1}) → 3
maxMirror({1, 2, 1, 4}) → 3
maxMirror({7, 1, 2, 9, 7, 2, 1}) → 2

Source

My Solution:

public int maxMirror(int[] nums) {
 int maxMirror=0 , mirrorCount=0;
            int len=nums.length;
            if(len<2) return len;
            for(int i=0 , j=len , k=0 , l=0 ; i<len-1 ; i++){
                // look for the currentvalue in the array
                while(--j>i && nums[j]!=nums[i]);
                if(j==i){ // no mirror starts from this val! check the next val
                    j=len-1; // next search must start from the end
                    continue;
                }
                else{ // found a mirror
                    k=i; // store boundaries of the mirror
                    l=j;
                    mirrorCount++;
                                        
                    while( (++k <= l && --j >= i) && (nums[k] == nums[j])  )
                        mirrorCount++;
                    if(mirrorCount > maxMirror)
                        maxMirror=mirrorCount;
                  
                    k=0 ; j=len; mirrorCount=0;
                }
            }// end for
            return maxMirror;
}

Sunday, April 25, 2010

seriesUp:Solutions for Javabat:13



Given integer n, create an array with the pattern {1,  1, 2, 1, 2, 3, ... 1, 2, 3 .. n} (spaces added to show the grouping). Note that the length of the array will be 1 + 2 + 3 ... + n, which is known to sum to exactly n*(n + 1)/2.

seriesUp(3) → {1, 1, 2, 1, 2, 3}
seriesUp(4) → {1, 1, 2, 1, 2, 3, 1, 2, 3, 4}
seriesUp(2) → {1, 1, 2}

Source

An excellent Array question , I have posted a similar question before (squareIn). First thing to be done is declare a target array , as it’s size can be determined by the n*(n+1)/2 .

public int[] seriesUp(int n) {
  int x[]= new int[n*(n+1)/2];
  
  for(int i=0, k=0; i<n; i++)
  {
    for(int j=0; j<=i;j++ ){
        x[k]=j+1;
        k++;
    }
  }
  return x;
}

Thursday, April 22, 2010

linearIn: Solutions for Javabat:12


Question:
Given two arrays of ints sorted in increasing order, outer and inner, return true if all of the numbers in inner appear in outer. The best solution makes only a single "linear" pass of both arrays, taking advantage of the fact that both arrays are already in sorted order.

linearIn({1, 2, 4, 6}, {2, 4}) → true
linearIn({1, 2, 4, 6}, {2, 3, 4}) → false
linearIn({1, 2, 4, 4, 6}, {2, 4}) → true

Source:

public boolean linearIn(int[] outer, int[] inner) {
  boolean b[]=new boolean[inner.length];
  boolean b1=true;
  
  for(int i=0;i<inner.length;i++){
     for(int j=0 ; j<outer.length;j++){
        if(inner[i]==outer[j])
           b[i]=true;
     }
  }
  for(boolean b2:b)
    b1 &= b2;
    
  return b1;  
}
 
 

Wednesday, April 21, 2010

canBalance:Solutions for Javabat:11



Given a non-empty array, return true if there is a place to split the array so that the sum of the numbers on one side is equal to the sum of the numbers on the other side.

canBalance({1, 1, 1, 2, 1}) → true
canBalance({2, 1, 1, 2, 1}) → false
canBalance({10, 10}) → true

Source

Possible solution is to make a pass on each element and calculate the sum of elements of to it’s right side and left side .

public boolean canBalance(int[] nums) {
  int sumleft=0,sumaright=0;
  
  for(int i=0 ; i<nums.length;i++ , sumbfor=0 , sumaftr=0){
     
     for(int j=0 ; j<i ; j++)
         sumleft+=nums[j];
     
     for(int k=i; k<nums.length;k++)
         sumright+=nums[k];
     
     if(sumleft==sumright)
       return true;
  }
  
  return false;
}
 
 

Sunday, April 18, 2010

fix34:Solutions for Javabat:10


Return an array that contains exactly the same numbers as the given array, but rearranged so that every 3 is immediately followed by a 4. Do not move the 3's, but every other number may move. The array contains the same number of 3's and 4's, every 3 has a number after it that is not a 3 or 4, and a 3 appears in the array before any 4.

fix34({1, 3, 1, 4}) → {1, 3, 4, 1}
fix34({1, 3, 1, 4, 4, 3, 1}) → {1, 3, 4, 1, 1, 3, 4}
fix34({3, 2, 2, 4}) → {3, 4, 2, 2}

Source

public int[] fix34(int[] nums) {
int newA[]=new int[nums.length];
for(int i=0 , index4=0 ; i< nums.length ; i++){
if(nums[i]==3 && i<nums.length-1){
newA[i]=3;
// find a four
for(int j=index4;j<nums.length;j++){
if(nums[j]==4){
nums[j]=newA[j]=nums[i+1];
nums[i+1]=newA[i+1]=4;
index4=i+2;
break;
}  // end if
}// end inner for
}// end if
else if(newA[i]==0) newA[i]=nums[i];
}
return newA;
}
 
 
Blogger Templates http://slots.to/