count_e Reflections on WriteUp 1 1

advertisement
ReflectionsonWriteUp1
1
Thecount_emethod
Defineamethodnamedcount_ethatacceptsaStringasinputandreturnsthenumberof
timesthechar‘e’occurs,asanint.
Forthecount_emethodanaturalapproachistoinspecteachcharacteroftheString,
andcounthowmanyofthesearetheletter‘e’:
‘s’istheparameterofthemethodnamed‘count_e’.
Itisalocalvariablewhoseinitialvalueisgivenby
‘count’isalocalvariable;it
willbeusedtokeeptrackof
howmany‘e’charactersare
seenintheStrings.
Atthecompletionofthe
methodthevalueofthe
‘count’variableisreturned.
Thisreturnedvalue
becomesthevalueofthe
methodcallexpression.
Thevalueoftheexpression
count_e(“electric”)is2,since
therearetwo‘e’characters
in“electric”.
public int count_e(String s) {
int count = 0;
for (int j=0; j<s.length(); j++) {
if (s.charAt(j) == 'e') {
count++;
}
}
return count;
}
Thevalueofthe‘count’
variableisincremented,but
onlyincasetheexpression
controllingtheif-statement
istrue.
theargumentprovidedinamethodcall.For
example,“electric”istheargumentinthecall
count_e(“electric”)
Theforloopiscontrolledbythevalueofthelocal
variable‘j’,whosevalueisusedasanindexintothe
String‘s’.ValidindicesforaStringrangefrom0
(zero)toonelessthanthelengthoftheString.
Thisexpressionistrueifandonlyifthecharacterin
thej-thpositionoftheStringsis‘e’.
Adiagramshowingtheflowofcontrolthroughthiscodeisgivenonthenextpage.
ReflectionsonWriteUp1
2
‘s’isassignedthevalueof
themethodcall’sargument
‘count’isassigned0(zero)
‘j’isassigned0(zero)
Is‘j’lessthan
s.length()?
No(false)
Yes(true)
Iss.charAt(j)
equalto‘e’?
No(false)
‘j’isassignedthecurrent
valueof‘j’plus1
Returnfromthemethod,
withthevalueofthevariable
‘count’asthevalueofthe
methodcall.
Yes(true)
‘count’isassignedthecurrent
valueof‘count’plus1
ReflectionsonWriteUp1
3
Thecount_one_charmethod
Defineamethodnamedcount_one_charthatacceptsaStringandacharasinputand
returnsthenumberoftimesthecharoccursintheString,asanint.
Thecount_one_charmethodisasimplegeneralizationofthecount_emethod:
Asecondparameterhasbeenaddedtothemethod,
public int count_one_char(String s, char c) {
int count = 0;
for (int j=0; j<s.length(); j++) {
if (s.charAt(j) == c) {
count++;
}
}
return count;
}
oftypechar.Thisparameterallowsthecallerto
specifywhichchartocount.
Thisexpressionistrueifandonlyifthecharacterin
thej-thpositionoftheStringsisthesameasthe
parameter,c.
Notethatthecount_emethodcouldbedefinedintermsofcount_one_charas
follows:
public int count_e(String s) {
return count_one_char(s,’e’);
}
ReflectionsonWriteUp1
4
Thecount_two_charsmethod
Defineamethodnamedcount_two_charsthatacceptsaStringandtwocharsasinput(i.e.
ithasthreeparametersintotal).Assumingthatthetwocharparametersarenamedcand
d,definethismethodsothatitreturns,asanint,thenumberoftimesthecharcoccursin
theinputaddedtothenumberoftimesthechardoccursintheinput.
Thecount_two_charsmethodfollowsthesamepatternasthecount_one_chars
method,exceptthateachofthetwocharsofinterestarecheckedforseparatelyin
itsownifstatement:
public int count_two_chars(String s, char c, char d) {
int count = 0;
for (int j=0; j<s.length(); j++) {
if (s.charAt(j) == c) {
count++;
}
if (s.charAt(j) == d) {
count++;
}
}
return count;
}
Thismethodcouldbedefined(somewhatlessefficientlysinceithastotraverses
twice)intermsofcount_one_charasfollows:
public int count_two_chars(String s, char c, char d) {
return count_one_char(s,c) + count_one_char(s,d);
}
ReflectionsonWriteUp1
5
Thecount_chars_in_Stringmethod
Defineamethodnamedcount_chars_in_StringthatacceptstwoStringsasinput.Assuming
thatthetwoparametersarenamedsandcharacters,definethismethodsothatitreturns,
asanint,thenumberoftimesanyofthecharsinthesecondString(characters)occurin
thefirstString(s).
Thecount_chars_in_Stringmethodisageneralizationofthecount_one_charand
count_two_charsmethods.Insteadofdistinctparametersforeachofthecharacters
wewishtocount,allthecharactersaredeliveredtothemethodasaString–the
parameternamed‘characters’.
Thismethodcanbedefinedseveralways.Here’soneway,usingthecount_one_char
methodwedefinedabove:
public int count_chars_in_String(String s, String characters) {
int count = 0;
for (int i=0; i<characters.length(); i++) {
char target = characters.charAt(i);
count = count + count_one_char(s,target);
}
return count;
}
Wecanalsodefinethecount_chars_in_Stringmethodwithoutcalling
count_one_char,byreplicatingitsfunctionality:
public int count_chars_in_String(String s, String characters) {
int count = 0;
for (int i=0; i<characters.length(); i++) {
char target = characters.charAt(i);
for (int j=0; j<s.length(); j++) {
if (s.charAt(j) == target) {
count++;
}
}
}
return count;
}
ReflectionsonWriteUp1
6
TheisPalindromemethod
DefineamethodnamedisPalindromethatacceptsaStringasinputandreturns,asa
boolean,whethertheinputisapalindromeornot.Apalindromereadsthesameway
forwardandbackwards.Rememberthatuppercaseandlowercasecharactersaredistinct.
Thebasicinsighthereisthatapalindromeisamirror-imageofitself.Here'sa
possiblesolution:
public boolean isPalindrome(String s) {
for (int i=0; i<s.length()/2; i=i+1) {
if (s.charAt(i) != s.charAt(s.length()-1-i)) {
return false;
}
}
return true;
}
ThehasAdjacentRepeatsmethod
DefineamethodnamedhasAdjacentRepeatsthatacceptsaStringasinputandreturns,as
aboolean,whethertheinputhastwoadjacentcharacterswhichareidentical.Forexample
“book”has‘o’asanadjacentrepeat,whereas“oboe”doesnot.
Wehavetobecarefultokeeptheindexwithinbounds.Becausewe'relookingat
twoadjacentcharactersfromtheStringmycodestartstheloopatindex1rather
than0,andlooksatthecharsatindicesiand(i-1).Notethatif1isnotavalidindex
oftheinputStrings,andtheloopdoesn'trun,itmeansthatthelengthofsisless
than2.Ifso,therecouldnotpossiblybetwoadjacentcharacters,sincetheString
doesn'thavetwocharacters.Here'sapossiblesolution:
public boolean hasAdjacentRepeats(String s) {
for (int i=1; i<s.length(); i=i+1) {
if (s.charAt(i) == s.charAt(i-1)) {
return true;
}
}
return false;
}
ReflectionsonWriteUp1
7
ThefirstIndexOfAdjacentRepeatsmethod
DefineamethodnamedfirstIndexOfAdjacentRepeatsthatacceptsaStringasinputand
returns,asanint,thelowestindexatwhichtwo(ormore)adjacentcharacterscanbe
foundintheinput,ifthereareadjacentrepeats.Otherwisethemethodmustreturn-1.For
theinput“book”theanswermustbe1.Fortheinput“oboe”theanswermustbe-1.
Similartothepreviousproblem.Here'sapossiblesolution:
public int firstIndexOfAdjacentRepeats(String s) {
for (int i=1; i<s.length(); i=i+1) {
if (s.charAt(i) == s.charAt(i-1)) {
return i-1;
}
}
return -1;
}
ThereplaceVowelsmethod
DefineamethodnamedreplaceVowelsthatacceptsaStringasinputandreturnsanew
StringwhichisjustliketheinputStringexceptthatallvowelshavebeenreplacedby‘*’.
Forexample,forinput“book”thereturnedvaluemustbe“b**k”.Assumethatthe
characters‘a’,‘e’,‘i’,‘o’and‘u’(andtheiruppercaseequivalents)arevowels.
Similartothepreviousproblem.Here'sapossiblesolution:
public String replaceVowels(String s) {
String answer = "";
for (int i=0; i<s.length(); i=i+1) {
char ch = s.charAt(i);
if (isVowel(ch)) {
answer = answer + '*';
}
else {
answer = answer + ch;
}
}
return answer;
}
private boolean isVowel(char ch) {
return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';
}
ReflectionsonWriteUp1
8
ThereplaceCharactersmethod
DefineamethodnamedreplaceCharactersthatacceptstwoStrings(calltheminputand
targets)andachar(callitc)andreturnsanewStringidenticaltoinputexceptthatany
characterfromtargetsisreplacedbyc.Forexample,replaceCharacters(“banana”,”bn”,’?’)
mustreturn“?a?a?a”.
Similartothepreviousproblem.Here'sapossiblesolution:
public String replaceCharacters(String s, String cs, char rep) {
String answer = "";
for (int i=0; i<s.length(); i=i+1) {
char ch = s.charAt(i);
if (isIn(ch,cs)) {
answer = answer + rep;
}
else {
answer = answer + ch;
}
}
return answer;
}
private boolean isIn(char ch, String cs) {
for (int i=0; i<cs.length(); i=i+1) {
if (ch == cs.charAt(i)) {
return true;
}
}
return false;
}
ReflectionsonWriteUp1
9
Thefirstwrite-up
Therewereseveralversionsofthefirstwrite-up.Herearepossiblesolutionsto
them.
VERSION1(SEEVIDEOASWELL)
package code;
public class WriteUp {
/*
* Define this method so that it returns a new String which
* contains all the characters from input that are at an even
* index input, none of the characters that are at an odd index.
*
* For example, solution("lasjdfk") must return "lsdk".
*/
public String solution(String input) {
String answer = "";
for (int i=0; i<input.length(); i=i+2) {
answer = answer + input.charAt(i);
}
return answer;
}
}
ReflectionsonWriteUp1
10
VERSION2
package code;
public class WriteUp {
/*
* Define this method so that it returns a new String which
* has exactly same characters as input, in the same order,
* except that any punctuation character ( . , ! ? : ; ) is
* doubled.
*
* You may assume that the input String is not null.
*
* For example:
*
solution("Hi, there!") must return "Hi,, there!!"
*
solution("") must return ""
*
solution("Hi there") must return "Hi there"
*
*/
public String solution(String input) {
String answer = "";
for (int i=0; i<input.length(); i=i+1) {
char ch = input.charAt(i);
answer = answer + ch;
if (punctuation(ch)) {
answer = answer + ch;
}
}
return answer;
}
private boolean punctuation(char ch) {
return ch == '.' || ch == ',' || ch == ':' ||
ch == ';' || ch == '!' || ch == '?';
}
}
ReflectionsonWriteUp1
11
VERSION3
package code;
public class WriteUp {
/*
* Define this method so that it returns a new String consisting
* of all the characters from input, in the same order, except
* that after each punctuation character ( . , ! ? : ; ) a dash
* ( - ) is inserted.
*
* You may assume that the input String is not null.
*
* For example:
* For example, solution("Hi, there!") must return "Hi,- there!-"
* For example, solution("") must return ""
* For example, solution("Hi, there") must return "Hi, there"
*/
public String solution(String input) {
String answer = "";
for (int i=0; i<input.length(); i=i+1) {
char ch = input.charAt(i);
answer = answer + ch;
if (punctuation(ch)) {
answer = answer + '-';
}
}
return answer;
}
private boolean punctuation(char ch) {
return ch == '.' || ch == ',' || ch == ':' ||
ch == ';' || ch == '!' || ch == '?';
}
}
ReflectionsonWriteUp1
12
VERSION4
package code;
public class WriteUp {
/*
* Define this method so that it returns a new String consisting
* of the the same characters as input, in the same order, except
* that the new String does not include any of the following six
* punctuation characters: . , ! ? : ;
*
* You may assume that the input String is not null.
*
* For example:
* solution("Hi, there!") must return "Hi there"
* solution("") must return ""
* solution("Hi there") must return "Hi there"
*/
public String solution(String input) {
String answer = "";
for (int i=0; i<input.length(); i=i+1) {
char ch = input.charAt(i);
if (!punctuation(ch)) {
answer = answer + ch;
}
}
return answer;
}
private boolean punctuation(char ch) {
return ch == '.' || ch == ',' || ch == ':' ||
ch == ';' || ch == '!' || ch == '?';
}
}
Download