Solved

string challenge

Posted on 2014-10-10
14
227 Views
Last Modified: 2014-10-13
Hi,

I was trying below challenge

http://codingbat.com/prob/p196441

I did not understand the requirement to proceed.

Given a non-empty string and an int N, return the string made starting with char 0, and then every Nth char of the string. So if N is 3, use char 0, 3, 6, ... and so on. N is 1 or more.

everyNth("Miracle", 2) → "Mrce"
everyNth("abcdefg", 2) → "aceg"
everyNth("abcdefg", 3) → "adg"


 Please advise
0
Comment
Question by:gudii9
14 Comments
 
LVL 84

Expert Comment

by:ozo
ID: 40373338
return str.replaceAll("(.).{0,"+(n-1)+"}","$1");
0
 
LVL 84

Expert Comment

by:ozo
ID: 40373373
everyNth("Miracle", 2) → "Mrce"
everyNth("abcdefg", 2) → "aceg"
everyNth("abcdefg", 3) → "adg"
0
 
LVL 14

Assisted Solution

by:Geisrud
Geisrud earned 100 total points
ID: 40373476
Here's my algorithm/solution (does the same thing as Ozo's solution, but my Java-Fu is weak, unoptimized, and overly verbose):

*Create a new String to hold the result.
*Use a for loop to parse through the string str they give you.
*At each n grab that char and append it to your new string
*Return your string
0
 
LVL 26

Assisted Solution

by:dpearson
dpearson earned 100 total points
ID: 40374477
You may find a loop like this gets you started...

  for (int pos = 0 ; pos < str.length() ; pos += n) {
      // Add the character at 'pos' to the output
  }

Doug
0
 
LVL 7

Author Comment

by:gudii9
ID: 40375267
public String everyNth(String str, int n) {
String s="";
    for (int pos = 0 ; pos < str.length() ; pos += n) {
      // Add the character at 'pos' to the output
      
      return (s+str.substring(pos-1, pos));
  }
  return null;
}

Open in new window


I tried as above
Test cases failing as below

Expected      Run            
everyNth("Miracle", 2) → "Mrce"      "Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (line number:6)"      X         
everyNth("abcdefg", 2) → "aceg"      "Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (line number:6)"      X         
everyNth("abcdefg", 3) → "adg"      "Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (line number:6)"      X         
everyNth("Chocolate", 3) → "Cca"      "Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (line number:6)"      X         
everyNth("Chocolates", 3) → "Ccas"      "Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (line number:6)"      X         
everyNth("Chocolates", 4) → "Coe"      "Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (line number:6)"      X         
everyNth("Chocolates", 100) → "C"      "Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (line number:6)"


Please advise
0
 
LVL 7

Author Comment

by:gudii9
ID: 40375273
public class TEst13 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		everyNth("hello", 2);
	}
	
	public static String everyNth(String str, int n) {
		String s="";
		    for (int pos = 0 ; pos < str.length() ; pos += n) {
		      // Add the character at 'pos' to the output
		      
		      return (s+str.substring(pos-1, pos));
		  }
		  return null;
		}

}

Open in new window


i get

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
      at java.lang.String.substring(Unknown Source)
      at TEst13.everyNth(TEst13.java:14)
      at TEst13.main(TEst13.java:6)
0
 
LVL 84

Expert Comment

by:ozo
ID: 40375354
If you write it that way, you'd want to start at pos=0

You also don't want to do the return inside the loop
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 7

Author Comment

by:gudii9
ID: 40375662
public class Test10 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		everyNth("hello", 2);
	}
	
	public static String everyNth(String str, int n) {
		String s="";
		String str2 = null;
		    for (int pos = 0 ; pos < str.length() ; pos += n) {
		      // Add the character at 'pos' to the output
		      
		      str2=(s+str.substring(pos-1, pos));
		  }
		  return str2;
		}

}

Open in new window


i moved return to outside. I thought i started at pos is 0 since my for loop checks pos=0.

Please advise
0
 
LVL 84

Expert Comment

by:ozo
ID: 40375666
pos=0
Sorry, I meant to say pos = 1
but rather than adjust that part, it may be preferable to change
(pos-1, pos) to (pos, pos+1)
that way the end condition wouldn't need to be adjusted too.


You are getting closer, but when you see the results, consider also why you are using both s and str2.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40375684
public class Test10 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String str3=everyNth("hello", 2);
		System.out.println("str3 value is"+str3);
	}
	
	public static String everyNth(String str, int n) {
		String s="";
		String str2 = null;
		    for (int pos = 0 ; pos < str.length() ; pos += n) {//i see length as 5 and pos started at 0
		      // Add the character at 'pos' to the output
		      
		     str2=(s+str.substring(pos, pos+1));
		  }
		  return str2;
		}

}

Open in new window


i modified further.

when i debug on eclipse i see h  then l then o

but my output only gives o
Console output is

str3 value iso
0
 
LVL 84

Expert Comment

by:ozo
ID: 40375688
Do you see why you only get o?  Do you understand what happened to the h then l?
Can you think of a way to get them in the output?
0
 
LVL 7

Author Comment

by:gudii9
ID: 40376946
somehow it is putting only last character not the before ones(it is kind of overriding before ones not sure why yet)


something needs to be tweaked below

str2=(s+str.substring(pos, pos+1));


not sure yet what
0
 
LVL 84

Accepted Solution

by:
ozo earned 300 total points
ID: 40376969
Consider why do you need both str2 and s?

Hint: you don't
0
 
LVL 7

Author Comment

by:gudii9
ID: 40377023
public class Test11 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String str3=everyNth("Miracle", 2);
		System.out.println("str3 value is-->"+str3);
	}
	
	public static String everyNth(String str, int n) {
		String s="";
		//String str2 = null;
		    for (int pos = 0 ; pos < str.length() ; pos += n) {//i see length as 5 and pos started at 0
		      // Add the character at 'pos' to the output
		      
		     s=(s+str.substring(pos, pos+1));
		  }
		  return s;
		}

}

Open in new window


you are right. i removed the extra one and concatenated to same string 's'

now all test cases are happy

Expected      Run            
everyNth("Miracle", 2) → "Mrce"      "Mrce"      OK         
everyNth("abcdefg", 2) → "aceg"      "aceg"      OK         
everyNth("abcdefg", 3) → "adg"      "adg"      OK         
everyNth("Chocolate", 3) → "Cca"      "Cca"      OK         
everyNth("Chocolates", 3) → "Ccas"      "Ccas"      OK         
everyNth("Chocolates", 4) → "Coe"      "Coe"      OK         
everyNth("Chocolates", 100) → "C"      "C"      OK
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Eclipse IDE - Cannot copy/paste from console output 8 132
Re-position the objects 7 97
jar file executable 12 43
even odd program using while loop 3 29
How to remove superseded packages in windows w60 or w61 installation media (.wim) or online system to prevent unnecessary space. w60 means Windows Vista or Windows Server 2008. w61 means Windows 7 or Windows Server 2008 R2. There are various …
If you haven’t already, I encourage you to read the first article (http://www.experts-exchange.com/articles/18680/An-Introduction-to-R-Programming-and-R-Studio.html) in my series to gain a basic foundation of R and R Studio.  You will also find the …
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.

895 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

16 Experts available now in Live!

Get 1:1 Help Now