Solved

deFront challenge

Posted on 2015-01-15
33
82 Views
Last Modified: 2015-02-05
Hi,

I am trying below challenge

http://codingbat.com/prob/p110141



Given a string, return a version without the first 2 chars. Except keep the first char if it is 'a' and keep the second char if it is 'b'. The string may be any length. Harder than it looks.

deFront("Hello") → "llo"
deFront("java") → "va"
deFront("away") → "aay"

I did not understand challenge clearly. can you please advise. Thanks in advance
0
Comment
Question by:gudii9
  • 16
  • 7
  • 6
  • +1
33 Comments
 
LVL 35

Assisted Solution

by:Kimputer
Kimputer earned 166 total points
ID: 40552237
I will use normal language, you will have to do the exact coding.

First of all, set aside the part you will definitely need, i.e. the last part, which is substring starting at 3.
Then do a compose test of substring 1 to 1 for a. If it is an a, set aside the a, otherwise make the result empty. Also substring 2 to 2 for the letter b. Again, make it b or empty.
Append those two result to the front of first result mentioned earlier.
0
 
LVL 31

Expert Comment

by:awking00
ID: 40553607
The challenge basically says return the string without the first two characters with the exceptions that, if the first character is an a, keep it and/or if the second character is a b, then keep it. So given the first two examples of "Hello" and "java", neither have a first character of a or a second character of b, so it returns the string without the first two characters. In the third example, "away", since a is the first character keep it but also return the remaining string without the first two characters. I would assume that a string like "ebay" would return "eay" (since b is the second character) or a string like "about" would return "about" (since a is the first character and b is the second character).
0
 
LVL 35

Expert Comment

by:Kimputer
ID: 40553624
"ebay" would return "eay"

I'm pretty sure it should be "bay"
0
 
LVL 31

Expert Comment

by:awking00
ID: 40553662
public String deFront(String str) {    
  String remainStr = str.substring(2);
  String a = "";
  String b = "";
  if (str.startsWith("a")) { a = "a"; }
  if (str.startsWith("b", 1)) {	b = "b"; }
  
  return a + b + remainStr;
}

Open in new window

0
 
LVL 31

Expert Comment

by:awking00
ID: 40553673
Kimputer, thanks for catching my error. Of course, it should be "bay" which is what my code above would return.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40554226
"ebay" would return "eay"


I'm pretty sure it should be "bay"

i too thought it should return "eay" based on comment ID: 40553607.
(by the way how to insert comment like ID: 40553607 as link. I do not know that trick. please advise)

I wonder why it should be "bay"?
0
 
LVL 84

Assisted Solution

by:ozo
ozo earned 167 total points
ID: 40554454
"keep the first char if it is 'a' and keep the second char if it is 'b'."
"ebay"
the second character is b, so keep it
the first character is not a, so don't keep it

For an internal link within the same question, add "http:#a" to the ID
http:#a40553607
(look at the URL in your browser navigation window)
0
 
LVL 7

Author Comment

by:gudii9
ID: 40567189
0
 
LVL 7

Author Comment

by:gudii9
ID: 40567191
Test passed
0
 
LVL 7

Author Comment

by:gudii9
ID: 40567193
For an internal link within the same question, add "http:#a" to the ID
http:#a40553607

How to do in different question
0
 
LVL 7

Author Comment

by:gudii9
ID: 40567288
public String deFront(String str) {  

String st=str;  
  
  if(st.substring(0,1).equals("a"))
  {
   st=st;
   }
   else
   {
   st=st.substring(1);
   }
   
   
   
     
  if(st.substring(1,2).equals("b"))
  {
   st=st;
   }
   else
   {
   st=st.substring(0,1)+st.substring(2);
   }
   return st;
}

Open in new window


i tried as above failing some test cases. please advise
Expected	Run		
deFront("Hello") → "llo"	"elo"	X	    
deFront("java") → "va"	"aa"	X	    
deFront("away") → "aay"	"aay"	OK	    
deFront("axy") → "ay"	"ay"	OK	    
deFront("abc") → "abc"	"abc"	OK	    
deFront("xby") → "by"	"b"	X	    
deFront("ab") → "ab"	"ab"	OK	    
deFront("ax") → "a"	"a"	OK	    
deFront("axb") → "ab"	"ab"	OK	    
deFront("aaa") → "aa"	"aa"	OK	    
deFront("xbc") → "bc"	"b"	X	    
deFront("bbb") → "bb"	"bb"	OK	    
deFront("bazz") → "zz"	"az"	X	    
deFront("ba") → ""	"Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 2 (line number:17)"	X	    
deFront("abxyz") → "abxyz"	"abxyz"	OK	    
deFront("hi") → ""	"Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 2 (line number:17)"	X	    
deFront("his") → "s"	"i"	X	    
deFront("xz") → ""	"Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 2 (line number:17)"	X	    
deFront("zzz") → "z"	"z"	OK	    
other tests
X	    
Correct for more than half the tests

Your progress graph for this problem

Open in new window

0
 
LVL 7

Author Comment

by:gudii9
ID: 40567315
public String deFront(String str) {  

String st=str;  
  
  if(st.substring(0,1).equals("a"))
  {
   st=st;
   }
   else
   {
   st=st.substring(1);
   }
   
   
   
     
  if(st.substring(1,2).equals("b"))
  {
   st=st;
   }
   else
   {
   st=st.substring(1);
   }
   return st;
}

Open in new window


i modified as above.
still failing some test cases
Expected	Run		
deFront("Hello") → "llo"	"llo"	OK	    
deFront("java") → "va"	"va"	OK	    
deFront("away") → "aay"	"way"	X	    
deFront("axy") → "ay"	"xy"	X	    
deFront("abc") → "abc"	"abc"	OK	    
deFront("xby") → "by"	"y"	X	    
deFront("ab") → "ab"	"ab"	OK	    
deFront("ax") → "a"	"x"	X	    
deFront("axb") → "ab"	"xb"	X	    
deFront("aaa") → "aa"	"aa"	OK	    
deFront("xbc") → "bc"	"c"	X	    
deFront("bbb") → "bb"	"bb"	OK	    
deFront("bazz") → "zz"	"zz"	OK	    
deFront("ba") → ""	"Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 2 (line number:17)"	X	    
deFront("abxyz") → "abxyz"	"abxyz"	OK	    
deFront("hi") → ""	"Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 2 (line number:17)"	X	    
deFront("his") → "s"	"s"	OK	    
deFront("xz") → ""	"Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 2 (line number:17)"	X	    
deFront("zzz") → "z"	"z"	OK	    
other tests

Open in new window

0
 
LVL 7

Author Comment

by:gudii9
ID: 40567329
I wonder how i got below output as llo for my code
st=st.substring(1);

Open in new window


deFront("Hello") → "llo"	"llo"	OK	

Open in new window


Hello
01234

since substring(1) should include begin index at 1 right

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int)

please advise
0
 
LVL 35

Expert Comment

by:Kimputer
ID: 40567362
Can you explain what you are doing? As the answer was already given by awking00 in the 4th post?
0
 
LVL 7

Author Comment

by:gudii9
ID: 40567666
i just want to try my own way also so that i know if i make some mistakes i can correct which probably could be other approach.
0
 
LVL 84

Expert Comment

by:ozo
ID: 40568058
How to do in different question
http://www.experts-exchange.com/Programming/Languages/Java/Q_28597672.html#a40553607
would work as a link from anywhere
0
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 
LVL 84

Expert Comment

by:ozo
ID: 40568059
Re: http:#a40567329
st=st.substring(1);
and then what happens to st after that?
0
 
LVL 35

Expert Comment

by:Kimputer
ID: 40570154
The code you wanted to try yourself has SEVERAL flaws.
You used fixed lengths (substring(x,y), so it means it will throw errors if you don't check for the correct length and you input something out of bounds.
Second, you have 2 pieces of code that do not comply with the problem:
Given a string, return a version without the first 2 chars.

This is never to be found in your code
Except keep the first char if it is 'a'
This is in your code, but with the exception flaw
and keep the second char if it is 'b'.
This code is only halfway implemented, and doesn't work in conjunction with previous line (negating it, therefore making the whole code flawed), and also have the exception flaw.
So, the problem required you to work out every line in unison, and you have two seperate if statements, so it will never work if you keep coding that way.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40570695
You used fixed lengths (substring(x,y), so it means it will throw errors if you don't check for the correct length and you input something out of bounds.
i thought i fixed this issue as below

public String deFront(String str) {  

String st=str;  
  
  if(str.length()>=2){
  if(st.substring(0,1).equals("a"))
  {
   st=st;
   }
   else
   {
   st=st.substring(1);
   }
   
   
   
     
  if(st.substring(1,2).equals("b"))
  {
   st=st;
   }
   else
   {
   st=st.substring(1);
   }
   }
   return st;
}

Open in new window


still get index out of bound for
eFront("ba") → ""	"Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 2 (line number:18)"	X

Open in new window


please advise
0
 
LVL 7

Author Comment

by:gudii9
ID: 40570699
and you have two seperate if statements
i thought i covered that?
please advise
0
 
LVL 35

Expert Comment

by:Kimputer
ID: 40570749
You really shouldn't start coding first. You should structure the logic first. You can tweak as many small things as you want, but the logic to begin with is failing. Write down the basics first, then build on it, and when it looks good, finally put it in code.

Your last piece of code already starts off with handling ONLY if the string is 2 or more. The original problem already stated it could be ANY length.

So write down the logic in normal short language first.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40570784
sure
0
 
LVL 31

Expert Comment

by:awking00
ID: 40571122
I agree with kimputer that you need to begin with the logic first before you start to code. When you do start to code, do it one "baby" step at a time. The basic logic should tell you that there are three parts to the result, the first character, the second character, and the rest of the characters in the string (if they exist). In your first attempt at the code, you show
Expected      Run            
deFront("Hello") → "llo"      "elo"      X      ==> Why would you test any further knowing this part is wrong? The first character is not "a" and the second character is not "b" and the remaining characters are "llo" so get this to work first before you try another test.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40573885
deFront("Hello") → "llo"      "elo"      X      ==> Why would you test any further knowing this part is wrong? The first character is not "a" and the second character is not "b" and the remaining characters are "llo" so get this to work first before you try another test.

i think i passed that as below

public String deFront(String str) {  

String st=str;  
  
  if(str.length()>=2){
  if(st.substring(0,1).equals("a"))
  {
   st=st;
   }
   else
   {
   st=st.substring(1);
   }
   
   
   
     
  if(st.substring(1,2).equals("b"))
  {
   st=st;
   }
   else
   {
   st=st.substring(1);
   }
   }
   return st;
}

Open in new window


still failing some tests.

Expected	Run		
deFront("Hello") → "llo"	"llo"	OK	    
deFront("java") → "va"	"va"	OK	    
deFront("away") → "aay"	"way"	X	    
deFront("axy") → "ay"	"xy"	X	    
deFront("abc") → "abc"	"abc"	OK	    
deFront("xby") → "by"	"y"	X	    
deFront("ab") → "ab"	"ab"	OK	    
deFront("ax") → "a"	"x"	X	    
deFront("axb") → "ab"	"xb"	X	    
deFront("aaa") → "aa"	"aa"	OK	    
deFront("xbc") → "bc"	"c"	X	    
deFront("bbb") → "bb"	"bb"	OK	    
deFront("bazz") → "zz"	"zz"	OK	    
deFront("ba") → ""	"Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 2 (line number:18)"	X	    
deFront("abxyz") → "abxyz"	"abxyz"	OK	    
deFront("hi") → ""	"Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 2 (line number:18)"	X	    
deFront("his") → "s"	"s"	OK	    
deFront("xz") → ""	"Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 2 (line number:18)"	X	    
deFront("zzz") → "z"	"z"	OK	    
other tests

Open in new window

I need to check further based on above posts
0
 
LVL 35

Expert Comment

by:Kimputer
ID: 40573938
You're still continuing on the wrong path, instead of listening to other advice.
0
 
LVL 31

Expert Comment

by:awking00
ID: 40577380
I'll repeat that the challenge involves three parts of a string, the first character, the second character, and the rest of the characters if they exist. How would you assign values to each of these parts? Once you figure that out, you can then return the concatenation of the three parts as one string.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40580347
the first character,
       the second character,
      and the rest of the characters if they exist. How would you assign values to each of these
      parts? Once you figure that out,

public String deFront(String str) {

		String st = null;  
                int strLen=str.length();
		String st1=str.substring(0,1);
		String st2=str.substring(1,2);
		String st3=str.substring(2);
		
		if(strLen<=2){
			
			st=str;
		}
		
		
		if(st1.equals("a")&& !st2.equals("b"))
		{
			st=st1+st3;
		}
		
		if(!st1.equals("a")&& st2.equals("b"))
		{
			st=st2+st3;
		}
		
		if(st1.equals("a")&& st2.equals("b"))
		{
			st=st3;
		}

             if(!st1.equals("a")&& !st2.equals("b"))
		{
			st=st3;
		}
		
		
		   return st;
		
		}

Open in new window


i think i am following what you are mentioning .

public class Test48 {

	/*I'll repeat that the challenge involves three parts of a string,
	 the first character,
	 the second character, 
	and the rest of the characters if they exist. How would you assign values to each of these 
	parts? Once you figure that out, 
	you can then return the concatenation of the three parts as one string.
	Given a string, return a version without the first 2 chars. Except keep the first char if it is
	 'a' and keep the second char if it is 'b'. The string may be any length. Harder than it looks.*/
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String output=deFront("abllo");
		System.out.println("output is-->"+output);
	}
	
	public static String deFront(String str) {
		 

		String st = null;  
        int strLen=str.length();
		String st1=str.substring(0,1);
		String st2=str.substring(1,2);
		String st3=str.substring(2);
		System.out.println("st1 is"+st1);
		System.out.println("st2 is"+st2);
		System.out.println("st3 is"+st3);
		
		if(strLen<=2){
			
			st=str;
		}
		
		
		if(st1.equals("a")&& !st2.equals("b"))
		{
			st=st1+st3;
		}
		
		if(!st1.equals("a")&& st2.equals("b"))
		{
			st=st2+st3;
		}
		
		if(st1.equals("a")&& st2.equals("b"))
		{
			st=st3;
		}
		
		
		/* 
		  if(str.length()>=2){
		  if(st.substring(0,1).equals("a"))
		  {
		   st=st;
		   }
		   else
		   {
		   st=st.substring(1);
		   }
		   
		   
		   
		     
		  if(st.substring(1,2).equals("b"))
		  {
		   st=st;
		   }
		   else
		   {
		   st=st.substring(1);
		   }
		   }*/
		

        if(!st1.equals("a")&& !st2.equals("b"))
	{
		st=st3;
	}
		   return st;
		
		}

}

Open in new window

i am failing in two test cases. please advise
0
 
LVL 7

Author Comment

by:gudii9
ID: 40580360
public String deFront(String str) {

		String st = null;  
                int strLen=str.length();
		String st1=str.substring(0,1);
		String st2=str.substring(1,2);
		String st3=str.substring(2);
		
		if(strLen>2){
		if(st1.equals("a")&& !st2.equals("b"))
		{
			st=st1+st3;
		}
		
		if(!st1.equals("a")&& st2.equals("b"))
		{
			st=st2+st3;
		}
		
		if(st1.equals("a")&& st2.equals("b"))
		{
			st=st1+st2+st3;
		}

             if(!st1.equals("a")&& !st2.equals("b"))
		{
			st=st3;
		}
		}


		if(strLen<=2){
			
			if(st1.equals("a")&& !st2.equals("b"))
		{
			st=st1+st3;
		}
		
		if(!st1.equals("a")&& st2.equals("b"))
		{
			st=st2+st3;
		}
		
		if(st1.equals("a")&& st2.equals("b"))
		{
			st=st1+st2;
		}


               if(!st1.equals("a")&& !st2.equals("b"))
		{
			st="";
		}



		}
		
		
		   return st;
		
		}

Open in new window


As above i paaed all tests. I am thinking i am following above suggestions. Please correct me where i am wrong and also suggest me on how to improve my code?
0
 
LVL 7

Author Comment

by:gudii9
ID: 40580414
my eclipse code is
public class Test48 {

	/*I'll repeat that the challenge involves three parts of a string,
	 the first character,
	 the second character, 
	and the rest of the characters if they exist. How would you assign values to each of these 
	parts? Once you figure that out, 
	you can then return the concatenation of the three parts as one string.
	Given a string, return a version without the first 2 chars. Except keep the first char if it is
	 'a' and keep the second char if it is 'b'. The string may be any length. Harder than it looks.*/
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String output=deFront("xyllo");
		System.out.println("output is-->"+output);
	}
	
	public static String deFront(String str) {

		String st = null;  
                int strLen=str.length();
		String st1=str.substring(0,1);
		String st2=str.substring(1,2);
		String st3=str.substring(2);
		
		if(strLen>2){
		if(st1.equals("a")&& !st2.equals("b"))
		{
			st=st1+st3;
		}
		
		if(!st1.equals("a")&& st2.equals("b"))
		{
			st=st2+st3;
		}
		
		if(st1.equals("a")&& st2.equals("b"))
		{
			st=st1+st2+st3;
		}

             if(!st1.equals("a")&& !st2.equals("b"))
		{
			st=st3;
		}
		}


		if(strLen<=2){
			
			if(st1.equals("a")&& !st2.equals("b"))
		{
			st=st1+st3;
		}
		
		if(!st1.equals("a")&& st2.equals("b"))
		{
			st=st2+st3;
		}
		
		if(st1.equals("a")&& st2.equals("b"))
		{
			st=st1+st2;
		}


               if(!st1.equals("a")&& !st2.equals("b"))
		{
			st="";
		}



		}
		
		
		   return st;
		
		}
}

Open in new window

0
 
LVL 31

Expert Comment

by:awking00
ID: 40580501
You've already been introduced to the ternary operator which is kind of a shortcut (your words) for if-then-else. Since you have three parts to your challenge, each of which can be determined by if-then-else why not just -
public static string deFront(String str) {

firstChar = str.substring(0,1).equals("a") ? "a" : "";
secondChar = str.substring(1,2).equals("b") ? "b" : "";
rest = str.length() <= 2? "" ; str.substring(2);

return firstChar + secondChar + rest;

}
0
 
LVL 7

Author Comment

by:gudii9
ID: 40580651
that pased all.
so 2 lessons for me
1. Alway break (challenge to sub units of 2 or more) and conquer(accordingly write code for each sub unit/part then concatenate /merge/join)
2. wheneve if else if comes to mind use shortcut operator.
0
 
LVL 31

Accepted Solution

by:
awking00 earned 167 total points
ID: 40581442
>>1. Alway break (challenge to sub units of 2 or more) and conquer(accordingly write code for each sub unit/part then concatenate /merge/join)
2. wheneve if else if comes to mind use shortcut operator<<

1. I would say always break down the challenge into each step required by the challenge logic and get them working individually before putting all of the steps together.
2.Not necessarily. While the ternary (not shortcut) operator is designed for if-then-else operations, it's perfectly okay to use if statements.

This-
firstChar = str.substring(0,1).equals("a") ? "a" : "";
is the same as this -
if (str.substring(0,1).equals("a") {
  firstChar = "a";
} else {
  first_chjar = "";
}
 Many people will find the more literal use of if and else easier to follow than the ? and : notation of the ternary operator.
0
 
LVL 84

Expert Comment

by:ozo
ID: 40592496
not shortcut
"short-circuit" in Java, C, et al., usually refers to the &&/|| operators skipping evaluation of their second operand when their first operand is false/true
"short-hand" (not to be confused with "shorthanded") usually refers to a shorter method of writing something.
"shortcut" usually refers to a shorter, quicker, or easier way to get to a place
Which may tend to get confused with either of the above concepts.
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Suggested Solutions

Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
When we want to run, execute or repeat a statement multiple times, a loop is necessary. This article covers the two types of loops in Python: the while loop and the for loop.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now