Link to home
Start Free TrialLog in
Avatar of gudii9
gudii9Flag for United States of America

asked on

mixString challenge

Hi,
I am working on below challenge
http://codingbat.com/prob/p125185
I tried my code as below
  public String mixString(String a, String b) {
  
  
  int aLen=a.length();
  int bLen=b.length();
  String newStr=null;

		 for(int i=0;i<=aLen-1;i++){
 for(int j=0;i<=bLen-1;j++){
newStr=a.substring(i,i+1)+b.substring(j,j+1);
continue;
}
}
return newStr;



}

Open in new window

I am getting below result
Expected      Run            
mixString("abc", "xyz") → "axbycz"      "Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 4 (line number:11)"      X         
mixString("Hi", "There") → "HTihere"      "Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 6 (line number:11)"      X         
mixString("xxxx", "There") → "xTxhxexre"      "Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 6 (line number:11)"      X         
mixString("xxx", "X") → "xXxx"      "Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 2 (line number:11)"      X         
mixString("2/", "27 around") → "22/7 around"      "Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 10 (line number:11)"      X         
mixString("", "Hello") → "Hello"      "null"      X         
mixString("Abc", "") → "Abc"      "null"      X         
mixString("", "") → ""      "null"      X         
mixString("a", "b") → "ab"      "Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 2 (line number:11)"      X         
mixString("ax", "b") → "abx"      "Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 2 (line number:11)"      X         
mixString("a", "bx") → "abx"      "Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 3 (line number:11)"      X         
mixString("So", "Long") → "SLoong"      "Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 5 (line number:11)"      X         
mixString("Long", "So") → "LSoong"      "Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 3 (line number:11)"      X         
other tests
X         
Your progress graph for this problem


how to  improve my approach, results and design of this challenge. How do i make a graphical venn or flow chart or some other relevant diagram to design it before writing code to decide best strategy?
 Please advise
ASKER CERTIFIED SOLUTION
Avatar of zzynx
zzynx
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of gudii9

ASKER

public class MixEx {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("values is---->"+mixString("abcd", "xyz"));

	}
	public static String mixString(String a, String b) {
		  
		  
		  int aLen=a.length();
		  int bLen=b.length();
		  String newStr=null;
		 
		 StringBuilder sb1=new StringBuilder();
		  StringBuilder sb2=new StringBuilder();
		   StringBuilder sb3=new StringBuilder();

				 for(int i=0;i<aLen-2;i++){
		 for(int j=0;i<bLen-2;j++){
			 System.out.println("11-->"+sb1.append(a.substring(i,i+1).toString()));
			 System.out.println("22-->"+sb2.append(b.substring(j,j+1).toString()));
		newStr=(sb1.append(a.substring(i,i+1)).toString()+(sb2.append(b.substring(j,j+1))).toString());
		continue;
		}
		}
		return newStr;



		}
}

Open in new window

above givieng below error . please advise

11-->a
22-->x
11-->aaa
22-->xxy
11-->aaaaa
22-->xxyyz
11-->aaaaaaa
Exception in thread "main" java.lang.StringIndexOutOfBoundsException
      at java.lang.String.substring(String.java:1148)
      at MixEx.mixString(MixEx.java:26)
      at MixEx.main(MixEx.java:9)

please advise
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of gudii9

ASKER

no end condition. let me modify
@gudii9  Didn't we tell you - in another thread - to please, please, please nicely indent your code?

About that code: why would you need TWO for loops?
Could you explain what you are trying to do in a comment next to each line of code?
Avatar of gudii9

ASKER

public class MixEx {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  System.out.println("values is---->" + mixString("abcd", "xyz"));

 }
 public static String mixString(String a, String b) {


  int aLen = a.length();
  int bLen = b.length();
  String newStr = null;

  StringBuilder sb1 = new StringBuilder();
  StringBuilder sb2 = new StringBuilder();
  StringBuilder sb3 = new StringBuilder();

  for (int i = 0; i < aLen - 2; i++) {
   for (int j = 0; i < bLen - 2; j++) {
    System.out.println("11-->" + sb1.append(a.substring(i, i + 1).toString()));
    System.out.println("22-->" + sb2.append(b.substring(j, j + 1).toString()));
    newStr = (sb1.append(a.substring(i, i + 1)).toString() + (sb2.append(b.substring(j, j + 1))).toString());
    continue;
   }
  }
  return newStr;



 }
}

Open in new window

sorry. Here is beatified code
Avatar of gudii9

ASKER

reason i chose 2 for loops is i wanted first character of a along with first character of b
then
2nd character of a with 2nd character of b till end.

i thought 2 for loops serve that purpose but i could be very well wrong??
Avatar of gudii9

ASKER

public class MixEx {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  System.out.println("values is---->" + mixString("abcd", "xyz"));

 }

 public static String mixString(String a, String b) {

  int aLen = a.length(); // find a length
  int bLen = b.length(); //find b length
  String newStr = null; //create a new string object

  StringBuilder sb1 = new StringBuilder(); //create string builder object
  StringBuilder sb2 = new StringBuilder(); //create string builder object
  StringBuilder sb3 = new StringBuilder(); //create string builder object

  for (int i = 0; i < aLen - 2; i++) { //loop each eleemnt of a string which is abcd here
   for (int j = 0; i < bLen - 2; j++) { //loop each element of b string whivch is xyz here
    System.out.println("11-->" + sb1.append(a.substring(i, i + 1).toString())); //get first character of a
    System.out.println("22-->" + sb2.append(b.substring(j, j + 1).toString())); //get first character of b
    newStr = (sb1.append(a.substring(i, i + 1)).toString() + (sb2
     .append(b.substring(j, j + 1))).toString()); //append first character of a and first chanracter of b and continue till loop ends
    continue;
   }
  }
  return newStr;

 }
}

Open in new window


please see my thought process in the comments. please correct me wherever needed
Avatar of gudii9

ASKER

public String mixString(String a, String b) {


 int aLen = a.length(); // find a length
 int bLen = b.length(); //find b length
 String newStr = null; //create a new string object

 StringBuilder sb1 = new StringBuilder(); //create string builder object
 StringBuilder sb2 = new StringBuilder(); //create string builder object
 StringBuilder sb3 = new StringBuilder(); //create string builder object

 for (int i = 0; i < aLen - 2; i++) { //loop each eleemnt of a string which is abcd here
  for (int j = 0; i < bLen - 2; j++) { //loop each element of b string whivch is xyz here
   //System.out.println("11-->"
   //+ //sb1.append(a.substring(i, i + 1).toString()));//get first character of a
   //System.out.println("22-->"
   //+ //sb2.append(b.substring(j, j + 1).toString()));//get first character of b
   newStr = (sb1.append(a.substring(i, i + 1)).toString() + (sb2
    .append(b.substring(j, j + 1))).toString()); //append first character of a and first chanracter of b and continue till loop ends
   continue;
  }
 }
 return newStr;

}

Open in new window


above fails all the tests

Expected	Run		
mixString("abc", "xyz") → "axbycz"	"Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 4 (line number:20)"	X	    
mixString("Hi", "There") → "HTihere"	"null"	X	    
mixString("xxxx", "There") → "xTxhxexre"	"Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 6 (line number:20)"	X	    
mixString("xxx", "X") → "xXxx"	"null"	X	    
mixString("2/", "27 around") → "22/7 around"	"null"	X	    
mixString("", "Hello") → "Hello"	"null"	X	    
mixString("Abc", "") → "Abc"	"null"	X	    
mixString("", "") → ""	"null"	X	    
mixString("a", "b") → "ab"	"null"	X	    
mixString("ax", "b") → "abx"	"null"	X	    
mixString("a", "bx") → "abx"	"null"	X	    
mixString("So", "Long") → "SLoong"	"null"	X	    
mixString("Long", "So") → "LSoong"	"null"	X	    
other tests
X	    
Your progress graph for this problem

Open in new window

for (int j = 0; i < bLen - 2; j++) { // when would this loop end?
maybe this is simpler
public String mixString(String a, String b) {
  if( a.length()>0&&b.length()>0 ){
      return a.substring(0,1)+b.substring(0,1)+mixString(a.substring(1),b.substring(1));
  }else{
      return a+b;
  }
}

Open in new window

Avatar of gudii9

ASKER

above is simpler using recursion right?


public String mixString(String a, String b) {
            int len = Math.min(a.length(), b.length());
            StringBuilder sb = new StringBuilder(a);
            char[] bs = b.toCharArray();
            for (int j = 0; j < len; j++) {
                  sb.insert(2*i + 1, bs[j]);
            }
            sb.append(a.length() < b.length() ? b.substring(a.length()) : "");
return sb.toString();
}

Open in new window


what is logic behind above code?
Avatar of gudii9

ASKER

public String mixString(String a, String b) {
            int len = Math.min(a.length(), b.length());
            StringBuilder sb = new StringBuilder(a);
            char[] bs = b.toCharArray();
            for (int j = 0; j < len; j++) {
                  sb.insert(2*i + 1, bs[j]);
            }
   sb.append(a.length() < b.length() ? b.substring(a.length()) : "");
return sb.toString();
}

Open in new window


above gives below error

Compile problems:


Error:      sb.insert(2*i + 1, bs[j]);
                  ^
i cannot be resolved


see Example Code to help with compile problems


please advise
Avatar of gudii9

ASKER

return a.substring(0,1)+b.substring(0,1)+mixString(a.substring(1),b.substring(1));


returning a substring of 0, 1 means a fist element concatenate to b first element then again call original method by passing a string from index 1 onwards and b string from index 1 onwards which then takes a next character and b next character and then calls orfinal method a from index 2 and b index 2??

when does this terminate finally??
Apparently awking00 typed i when they meant to type j
when does this terminate finally
when we don't return a.substring(0,1)+b.substring(0,1)+mixString(a.substring(1),b.substring(1));
reason i chose 2 for loops is i wanted first character of a along with first character of b then 2nd character of a with 2nd character of b till end.
That's EXACTLY what the code in my first post does.
It does that as long as the xth character exists for BOTH strings.
When it detects the end of one of the string, it appends the rest of the other string to the result.
Nice and clean. And it passes all test cases.
I wonder why you don't talk about it any further. What's wrong with that code?

To get the xth character of the first ànd the 2nd string, you don't need two loops.
One is enough.
Also, if this is (the start of) your first loop (using variable 'i')
for (int i = 0; i < aLen - 2; i++)

Open in new window

if you need a second loop using variable 'j', then you should use 'j' in EACH of the parts and hence don't write this:
for (int j = 0; i < bLen - 2; j++) 

Open in new window

Avatar of gudii9

ASKER

public String mixString(String a, String b) {
            int len = Math.min(a.length(), b.length());
            StringBuilder sb = new StringBuilder(a);
            char[] bs = b.toCharArray();
            for (int j = 0; j < len; j++) {
                  sb.insert(2*j + 1, bs[j]);
            }
   sb.append(a.length() < b.length() ? b.substring(a.length()) : "");
return sb.toString();
}

Open in new window


above pased all tests but i lost what i was doing below
  sb.insert(2*j + 1, bs[j]);

and also below
   sb.append(a.length() < b.length() ? b.substring(a.length()) : "");
Avatar of gudii9

ASKER

public String mixString(String a, String b) {
            int len = Math.min(a.length(), b.length());
            StringBuilder sa = new StringBuilder(a);
            char[] bs = b.toCharArray();
            for (int j = 0; j < len; j++) {
                  sa.insert(2*j + 1, bs[j]);
            }
   sa.append(a.length() < b.length() ? b.substring(a.length()) : "");
return sa.toString();
}

Open in new window


i renamedd variables a bit which passes all tests
Avatar of gudii9

ASKER

ID: 41439996
Another approach using StringBuilder -
public String mixString(String a, String b) {
            int len = Math.min(a.length(), b.length());
            StringBuilder sb = new StringBuilder(a);
            char[] bs = b.toCharArray();
            for (int j = 0; j < len; j++) {
                  sb.insert(2*i + 1, bs[j]);
            }
            sb.append(a.length() < b.length() ? b.substring(a.length()) : "");
return sb.toString();
}

above why are we doing 2*1+1 and then where we are adding each character of b string to a string each character?
Avatar of gudii9

ASKER

    char[] bs = b.toCharArray();
            for (int j = 0; j < len; j++) {

why we need for loop.

please advise on above approach?
can we do this using regular expression?
Avatar of gudii9

ASKER

public String mixString(String a, String b) {
            int len = Math.min(a.length(), b.length());
            StringBuilder sb = new StringBuilder(a);
            char[] bs = b.toCharArray();
            for (int j = 0; j < len; j++) {
                  sb.insert(2*i + 1, bs[j]);
            }
            sb.append(a.length() < b.length() ? b.substring(a.length()) : "");
return sb.toString();
}

Open in new window


above gives below error.
Compile problems:


Error:      sb.insert(2*i + 1, bs[j]);
                  ^
i cannot be resolved


see Example Code to help with compile problems
please advise
Avatar of gudii9

ASKER

public class MixString {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("is--->"+mixString("abc","xyz"));

	}
	public static String mixString(String a, String b) {
        int len = Math.min(a.length(), b.length());
        StringBuilder sb = new StringBuilder(a);
        char[] bs = b.toCharArray();
        for (int j = 0; j < len; j++) {
              sb.insert(2*j+ 1, bs[j]);
        }
        sb.append(a.length() < b.length() ? b.substring(a.length()) : "");
return sb.toString();
}
}

Open in new window


above gave below correct result. looks like both j only no i there
is--->axbycz
Avatar of gudii9

ASKER

public class MixString {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("is 11--->"+mixString("abc","wxyz"));

	}
	public static String mixString(String a, String b) {
        int len = Math.min(a.length(), b.length());
        System.out.println("len is"+len);
        StringBuilder sb = new StringBuilder(a);
        char[] bs = b.toCharArray();
        for (int j = 0; j < len; j++) {
        	System.out.println("j value 44-->"+j);
              sb.insert(2*j+ 1, bs[j]);
        }
        System.out.println("is 22"+(a.length() < b.length()));
        System.out.println("is 33"+(b.substring(a.length())));
        sb.append(a.length() < b.length() ? b.substring(a.length()) : "");
return sb.toString();
}
}

Open in new window


above gave correct below result
len is3
j value 44-->0
j value 44-->1
j value 44-->2
is 22true
is 33z
is 11--->awbxcyz

below code
public class MixString {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("is 11--->"+mixString("abcd","xyz"));

	}
	public static String mixString(String a, String b) {
        int len = Math.min(a.length(), b.length());
        System.out.println("len is"+len);
        StringBuilder sb = new StringBuilder(a);
        char[] bs = b.toCharArray();
        for (int j = 0; j < len; j++) {
        	System.out.println("j value 44-->"+j);
              sb.insert(2*j+ 1, bs[j]);
        }
        System.out.println("is 22"+(a.length() < b.length()));
        System.out.println("is 33"+(b.substring(a.length())));
        sb.append(a.length() < b.length() ? b.substring(a.length()) : "");
return sb.toString();
}
}

Open in new window


gives below error

len is3
j value 44-->0
j value 44-->1
j value 44-->2
is 22false
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
      at java.lang.String.substring(Unknown Source)
      at MixString.mixString(MixString.java:19)
      at MixString.main(MixString.java:6)

please advise
No correct indentation in your code = I even don't try to decode it anymore.
Sorry. We asked it already multiple times.
Avatar of gudii9

ASKER

public class MixString {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("is 11--->" + mixString("abcd", "xyz"));

	}

	public static String mixString(String a, String b) {
		int len = Math.min(a.length(), b.length());
		System.out.println("len is" + len);
		StringBuilder sb = new StringBuilder(a);
		char[] bs = b.toCharArray();
		for (int j = 0; j < len; j++) {
			System.out.println("j value 44-->" + j);
			sb.insert(2 * j + 1, bs[j]);
		}
		System.out.println("is 22" + (a.length() < b.length()));
		System.out.println("is 33" + (b.substring(a.length())));
		sb.append(a.length() < b.length() ? b.substring(a.length()) : "");
		return sb.toString();
	}
}

Open in new window


i got eclipse i can do it now as above
Avatar of gudii9

ASKER

error is

len is3
j value 44-->0
j value 44-->1
j value 44-->2
is 22false
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
      at java.lang.String.substring(Unknown Source)
      at MixString.mixString(MixString.java:20)
      at MixString.main(MixString.java:6)
Explanation of the error:

Your b string ("xyz") is 3 long.
Your a string ("abcd") is 4 long.

In this line
System.out.println("is 33" + (b.substring(a.length())));

Open in new window

you try to take the substring of "xyz" starting at position 4.
This string has no position 4. It only has positions 0, 1 and 2. (which correspond with the chars x, y and z)
Avatar of gudii9

ASKER

so how to tweak or modify my code to run successfully with above kind of strings four and three long?
I have the same question to you as in the other thread:
What is wrong with the (well documented) solution I posted earlier?
Avatar of gudii9

ASKER

nothing wrong. learning different approaches including fixing my approach
Avatar of gudii9

ASKER

public class MixString {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("is 11--->" + mixString("abcd", "xyz"));

	}

	public static String mixString(String a, String b) {
	//public String mixString(String a, String b) {
		  int aLen=a.length();
		  int bLen=b.length();
		  String newStr="";  // Start with an empty string

		  for(int i=0; i<aLen && i<bLen; i++){   // as long as there are characters in a ànd b
		      newStr += a.substring(i,i+1)+b.substring(i,i+1);  // add the next character from a and the next from b
		  }
		  if (aLen < bLen) {
		     newStr += b.substring(aLen); // Add the rest of b
		  } else if (bLen < aLen) {
		     newStr += a.substring(bLen); // Add the rest of a
		  }
		  
		  return newStr;
		}
}

Open in new window


above gave correct output

is 11--->axbyczd
Avatar of gudii9

ASKER

public class MixString {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("is 11--->" + mixString("abcd", "xyz"));

	}

	public static String mixString(String a, String b) {
		int len = Math.min(a.length(), b.length());
		System.out.println("len is" + len);
		StringBuilder strBuildA = new StringBuilder(a);
		char[] bChar = b.toCharArray();
		for (int j = 0; j < len; j++) {
			System.out.println("j value 44-->" + j);
			strBuildA.insert(2 * j + 1, bChar[j]);
			System.out.println("value 55-->" + strBuildA.toString());
		}
		System.out.println("is 22" + (a.length() < b.length()));
		// System.out.println("is 33" + (b.substring(a.length())));
		strBuildA.append(a.length() < b.length() ? b.substring(a.length()) : "");
		return strBuildA.toString();
	}
}

Open in new window


when i commented that line got correct output as below

len is3
j value 44-->0
value 55-->axbcd
j value 44-->1
value 55-->axbycd
j value 44-->2
value 55-->axbyczd
is 22false
is 11--->axbyczd
You would better replace:

System.out.println("is 33" + (b.substring(a.length())));
strBuildA.append(a.length() < b.length() ? b.substring(a.length()) : "");

Open in new window

by

if (a.length() < b.length()) {
    System.out.println("is 33" + (b.substring(a.length())));
    strBuildA.append(b.substring(a.length()));
}

Open in new window


when i commented that line got correct output as below
Good. Time to close this thread, I think.
Avatar of gudii9

ASKER

public class MixString {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("is 11--->" + mixString("abcd", "xyz"));

	}

	public static String mixString(String a, String b) {
		int len = Math.min(a.length(), b.length());
		System.out.println("len is" + len);
		StringBuilder strBuildA = new StringBuilder(a);
		char[] bChar = b.toCharArray();
		for (int j = 0; j < len; j++) {
			System.out.println("j value 44-->" + j);
			strBuildA.insert(2 * j + 1, bChar[j]);
			System.out.println("value 55-->" + strBuildA.toString());
		}
		System.out.println("is 22" + (a.length() < b.length()));
		// System.out.println("is 33" + (b.substring(a.length())));
		// strBuildA.append(a.length() < b.length() ? b.substring(a.length()) :
		// "");

		if (a.length() < b.length()) {
			System.out.println("is 33" + (b.substring(a.length())));
			strBuildA.append(b.substring(a.length()));
		}
		return strBuildA.toString();

		/*
		 * if (a.length() < b.length()) { System.out.println("is 33" +
		 * (b.substring(a.length())));
		 * strBuildA.append(b.substring(a.length())); }
		 */

	}
}

Open in new window

above gave correct output
len is3
j value 44-->0
value 55-->axbcd
j value 44-->1
value 55-->axbycd
j value 44-->2
value 55-->axbyczd
is 22false
is 11--->axbyczd