CSE116 Problem Set #3

advertisement
CSE116ProblemSet#3
ForeachofthefollowingproblemsyoushouldstartbywritingseveralJUnitteststhatwillverify
correctbehavior.Onceyouhavewrittenatleastfourdistincttestsforeachoftheproblems,begin
toimplementsolutionstoeachoftheproblems.Besuretorunyourunittestsoften.Theyarenot
necessarilyinorderofdifficulty.
1. DefineamethodnamedencodethatacceptsaStringasinputandreturnsanewString
whichistheoriginalStringencodedusingtheROT13cipher.Thissimplesubstitution
cipherisdescribedhere:
http://en.wikipedia.org/wiki/Substitution_cipher#Simple_substitution
Forexample,encode(“firefly”)mustproduce“sversyl”.Noticethatre-encodingtheencoded
Stringdecodesit:encode(“sversyl”)mustproduce“firefly”.
Forthepurposesofthisexercise,assumethatlowercaselettersarerotatedwithinthe
lowercaseletters,uppercaselettersarerotatedwithintheuppercaseletters,andnonlettersarenotrotated.Thus,encode(“338Davis”)mustproduce“338Qnivf”.
2. DefineamethodnamedencodethatacceptstwoStringsasinputandreturnsanewString
whichisthefirstofthetwoinputStringsencodedusingthesecondStringasakeywordfor
creatingamixedalphabet,asdescribedhere:
http://en.wikipedia.org/wiki/Substitution_cipher#Simple_substitution
Forthepurposesofthisexercise,assumethattheciphertextalphabetconsistsofonly
uppercaseletters.Seethe‘zebras’exampleonthereferencewebsite.
3. DefineamethodnamedencodethatacceptstwoStringsasinputandreturnsanewString
whichisthefirstofthetwoinputsStringsencodedusingthesecondStringasakeyword
usingtheVigenèrecipher,asdescribedhere(4thparagraph):
http://en.wikipedia.org/wiki/Substitution_cipher#Polyalphabetic_substitution
4. DefineamethodnamedanagramthatacceptstwoStringsasinputandreturnstrueifthe
twoStringsareanagramsofeachother(theycontainthesameletters,ignoringspacesand
capitalization),andfalseotherwise.Forexample,“listen”and“silent”areanagrams,asare
“TomMarvoloRiddle”and“IamLordVoldemort”.HINT:problemset2,question7.
5. Defineavoidmethodnamedswapthatacceptsanarrayofintandtwointvalues(callthem
andy)sothatitinterchangesthevaluesinlocationsxandyofthearray.Forexample,ifan
arrayisinitially(5,7,9,3)thenswappingthevaluesinpositions0and2changesthearray
to(9,7,5,3).
6. Defineamethodnamedzipacceptstwoequal-lengtharraysofints,andproducesanew
arrayofints.Theresultingarraymusthavealternatethevaluesfromthetwoinputarrays.
Forexample,ifthetwoinputarraysare(4,3,7,2,6)and(2,1,4,8,0)thentheresultmustbe
(4,2,3,1,7,4,2,8,6,0).
7. Defineamethodnamedmergewhichacceptstwopossiblyunequal-lengtharraysofints,
andproducesanewarrayofints.Assumethatthetwoinputarrayshavetheircontents
arrangedfromsmallesttolargest.Theresultingarraymusthavethevaluesfromthetwo
inputarraysarrangedinorderfromsmallesttolargest.Forexample,ifthetwoinputarrays
are(1,2,5,6,7)and(2,3,8,9)thentheresultmustbe(1,2,2,3,5,6,7,8,9).
Download