You are on page 1of 3

7/28/2015

ProgrammingAssignment1Checklist:Percolation

ProgrammingAssignment1Checklist:Percolation
FrequentlyAskedQuestions(General)
What'sachecklist?Theassignmentprovidestheprogrammingassignmentspecificationthechecklistprovidesclarifications,testdata,andhintsthatmightbe
helpfulincompletingtheassignment.
WhichJavaprogrammingenvironmentshouldIuse?Fornovices,werecommendthelightweightIDEDrJavaalongwiththecommandline.Ifyouuseour
MacOSXorWindowsinstaller,theneverythingshouldbeconfiguredandreadytogo.IfyouprefertouseadifferentIDE(suchasEclipse),that'sperfectlyfine
toojustbesurethatyouknowhowtodothefollowing:
Addstdlib.jarandalgs4.jartoyourJavaclasspath.
Entercommandlinearguments.
Usestandardinputandstandardoutput(and,ideally,redirectthemtoorfromafile).
Whataretheinputandoutputlibraries?WehavedesignedasetofeasytouseJavalibrariesinstdlib.jarforinputandoutputthatyouarerequiredtousein
thiscourse.HerearetheAPIs.
WherecanIfindtheJavacodeforthealgorithmsanddatastructuresfromlectureandthetextbook?Theyareinalgs4.jar.HerearetheAPIs.
HowcanIclasspathinthetextbooklibrariesfromthecommandline?IfyouuseourMacOSXorWindowsinstaller,thenyoucanautomaticallyclasspath
inthetextbooklibrariesusingthecommandsjavacalgs4andjavaalgs4(insteadofjavacandjava).
Ihaven'tprogrammedinJavainawhile.WhatmaterialdoIneedtoremember?ForareviewofourJavaprogrammingmodel(includingourinputand
outputlibraries),readSections1.1and1.2ofAlgorithms,4thEdition.
CanIusevariousJavalibrariesinthisassignment,suchasjava.util.LinkedList,java.util.ArrayList,java.util.TreeMap,andjava.util.HashMap?No.
YoushouldnotuseanyJavalibrariesuntilwehaveimplementedequivalentversionsinlecture.Oncewehaveintroducedtheminlecture,youarefreetouse
eithertheJavalibraryversionorourequivalent.YouarewelcometouseclassesintheJavalanguagesuchasMath.sqrt()andInteger.parseInt().
HowdoIthrowajava.lang.IndexOutOfBoundsException?Useathrowstatementlikethefollowing:
if(i<=0||i>N)thrownewIndexOutOfBoundsException("rowindexioutofbounds");

Yourcodeshouldnotattempttocatchanyexceptionsthiswillinterferewithourgradingscripts.
HowshouldIformatandcommentmycode?Herearesomerecommendedstyleguidelines.Belowaresomethatareparticularlyimportant(thoughwewill
notdeductforstyleinthiscourse).
Includeabold(orJavadoc)commentatthebeginningofeachfilewithyourname,date,thepurposeoftheprogram,andhowtoexecuteit.
Includeabold(orJavadoc)commentdescribingeverymethod.
Includeacommentdescribingeveryinstancevariable.
Indentconsistently,using3or4spacesforeachindentationlevel.Donotusehardtabs.
Donotexceed80charactersperline.Thisrulealsoappliestothereadme.txtfile.
Avoidunexplainedmagicnumbers,especiallyonesthatareusedmorethanonce.
FrequentlyAskedQuestions(Percolation)
Whatarethegoalsofthisassignment?
SetupaJavaprogrammingenvironment.
Useourinputandoutputlibraries.
Learnaboutascientificapplicationoftheunionfinddatastructure.
Measuretherunningtimeofaprogramandusethedoublinghypothesistomakepredictions.
Measuretheamountofmemoryusedbyadatastructure.
CanIadd(orremove)methodsto(orfrom)Percolation?No.YoumustimplementthePercolationAPIexactlyasspecified,withtheidenticalsetofpublic
methodsandsignaturesoryourassignmentwillnotbegraded.However,youareencouragedtoaddprivatemethodsthatenhancethereadability,
maintainability,andmodularityofyourprogram.Theoneexceptionismain()youarealwayspermittedtoaddthismethodtotestyourcode,butwewillnot
callitunlesswespecifyitinourAPI.
CanmyPercolationdatatypeassumetherowandcolumnindicesarebetween0andN1?No.TheAPIspecifiesthatvalidrowandcolumnindicesare
between1andN.
WhyisitsoimportanttoimplementtheprescribedAPI?WritingtoanAPIisanimportantskilltomasterbecauseitisanessentialcomponentofmodular
programming,whetheryouaredevelopingsoftwarebyyourselforaspartofagroup.WhenyoudevelopamodulethatproperlyimplementsanAPI,anyone
usingthatmodule(includingyourself,perhapsatsomelatertime)doesnotneedtorevisitthedetailsofthecodeforthatmodulewhenusingit.Thisapproach
greatlysimplifieswritinglargeprograms,developingsoftwareaspartofagroup,ordevelopingsoftwareforusebyothers.
Mostimportant,whenyouproperlyimplementanAPI,otherscanwritesoftwaretouseyourmoduleortotestit.Wedothisregularlywhengradingyour
programs.Forexample,yourPercolationStatsclientshouldworkwithourPercolationdatatypeandviceversa.Ifyouaddanextrapublicmethodto
PercolationandcallthemfromPercolationStats,thenyourclientwon'tworkwithourPercolationdatatype.Conversely,ourPercolationStatsclientmaynot
workwithyourPercolationdatatypeifyouremoveapublicmethod.
http://coursera.cs.princeton.edu/algs4/checklists/percolation.html

1/3

7/28/2015

ProgrammingAssignment1Checklist:Percolation

Howmanylinesofcodeshouldmyprogrambe?Youshouldstriveforclarityandefficiency.OurreferencesolutionforPercolation.javaisabout70lines,
plusatestclient.OurPercolationStats.javaclientisabout50lines.Ifyouarereimplementingtheunionfinddatastructure(insteadofreusingthe
implementationsprovided),youareonthewrongtrack.
WhatassumptionscanImakeabouttheinputtomain()inPercolationStats?Itcanbeanyvalidinput:anintegerN1andanintegerT1.Ingeneral,in
thiscourseyoucanassumethattheinputisofthespecifiedformat.ButyoudoneedtodealwithpathologicalcasessuchasN=1.
Whatshouldstddev()returnifTequals1?Thesamplestandarddeviationisundefined.WerecommendreturningDouble.NaN.
Afterthesystemhaspercolated,myPercolationVisualizercolorsinlightblueallsitesconnectedtoopensitesonthebottom(inadditiontothose
connectedtoopensitesonthetop).Isthis"backwash"acceptable?No,thisislikelyabuginPercolation.Itisonlyaminordeduction(becauseitimpacts
onlythevisualizerandnottheexperimenttoestimatethepercolationthreshold),sodon'tgocrazytryingtogetthisdetail.However,manystudentsconsiderthis
tobethemostchallengingandcreativepartoftheassignment(especiallyifyoulimityourselftooneunionfindobject).
%javaPercolationVisualizerinput10.txt

HowdoIgenerateasiteuniformlyatrandomamongallblockedsitesforuseinPercolationStats?Pickasiteatrandom(byusingStdRandomtogenerate
twointegersbetween1andN)andusethissiteifitisblockedifnot,repeat.
Idon'tgetreliabletiminginformationinPercolationStatswhenN=200.WhatshouldIdo?IncreasethesizeofN(sayto400,800,and1600),untilthe
meanrunningtimeexceedsitsstandarddeviation.
StyleandBugCheckers
Stylechecker.WerecommendusingCheckstyle5.5(andtheconfigurationfilecheckstyle.xml)tocheckthestyleofyourJavaprograms.Hereisalistof
availableCheckstylechecks.
Bugchecker.WerecommendusingFindBugs2.0.3(andtheconfigurationfilefindbugs.xml)toidentifycommonbugpatternsinyourcode.Hereisasummary
ofFindBugsBugdescriptions.
MacOSXandWindowsinstaller.IfyouusedourMacOSXorWindowsinstaller,theseprogramsarealreadyinstalledascommandlineutilities.Youcan
checkasinglefileormultiplefilesviathecommands:
%checkstylealgs4HelloWorld.java
%checkstylealgs4*.java
%findbugsalgs4HelloWorld.class
%findbugsalgs4*.class

NotethatCheckstyleinspectsthesourcecodeFindbugsinspectsthecompiledcode.
Eclipse.ForEclipseusers,thereisaCheckstylepluginforEclipseandaFindbugspluginforEclipse.
Caveat.Theappearanceofawarningmessagedoesnotnecessarilyleadtoadeduction(and,insomecases,itdoesnotevenindicateanerror).
Testing
Testing.Weprovidetwoclientsthatserveaslargescalevisualtraces.WehighlyrecommendusingthemfortestinganddebuggingyourPercolation
implementation.
Visualizationclient.PercolationVisualizer.javaanimatestheresultsofopeningsitesinapercolationsystemspecifiedbyafilebyperformingthefollowing
steps:
ReadthegridsizeNfromthefile.
CreateanNbyNgridofsites(initiallyallblocked).
Readinasequenceofsites(rowi,columnj)toopenfromthefile.Aftereachsiteisopened,drawfullsitesinlightblue,opensites(thataren'tfull)in
white,andblockedsitesinblackusingstandarddraw,withwithsite(1,1)intheupperlefthandcorner.
Theprogramshouldbehaveasinthismovieandthefollowingsnapshotswhenusedwithinput20.txt.
%javaPercolationVisualizerinput20.txt

http://coursera.cs.princeton.edu/algs4/checklists/percolation.html

2/3

7/28/2015

ProgrammingAssignment1Checklist:Percolation

50opensites

100opensites

150opensites

204opensites

250opensites

Sampledatafiles.Thedirectorypercolationcontainssomesamplefilesforusewiththevisualizationclient.Associatedwitheachinput.txtfileisanoutput
.pngfilethatcontainsthedesiredgraphicaloutputattheendoftheanimation.Forconvenience,percolationtesting.zipcontainsallofthesefilesbundled
together.
InteractiveVisualizationclient.InteractivePercolationVisualizer.javaissimilartothefirsttestclientexceptthattheinputcomesfromamouse(insteadoffrom
afile).IttakesacommandlineintegerNthatspecifiesthelatticesize.Asabonus,itwritestostandardoutputthesequenceofsitesopenedinthesameformat
usedbyPercolationVisualizer,soyoucanuseittoprepareinterestingfilesfortesting.Ifyoudesignaninterestingdatafile,feelfreetoshareitwithusand
yourclassmatesbypostingitinthediscussionforums.
PossibleProgressSteps
Thesearepurelysuggestionsforhowyoumightmakeprogress.Youdonothavetofollowthesesteps.
1. Considernotworryingaboutbackwashforyourfirstattempt.Ifyou'refeelingoverwhelmed,don'tworryaboutbackwashwhenfollowingthepossible
progressstepsbelow.Youcanreviseyourimplementationonceyouhaveabetterhandleontheproblemandhavesolvedtheproblemwithouthandling
backwash.
2. ForeachmethodinPercolationthatyoumustimplement(open(),percolates(),etc.),makealistofwhichWeightedQuickUnionUFmethodsmightbe
usefulforimplementingthatmethod.Thisshouldhelpsolidifywhatyou'reattemptingtoaccomplish.
3. Usingthelistofmethodsaboveasaguide,chooseinstancevariablesthatyou'llneedtosolvetheproblem.Don'toverthinkthis,youcanalways
changethemlater.Instead,useyourlistofinstancevariablestoguideyourthinkingasyoufollowthestepsbelow,andmakechangestoyourinstance
variablesasyougo.Hint:Atminimum,you'llneedtostorethegridsize,whichsitesareopen,andwhichsitesareconnectedtowhichothersites.Thelast
oftheseisexactlywhattheunionfinddatastructureisdesignedfor.
4. Planhowyou'regoingtomapfroma2dimensional(row,column)pairtoa1dimensionalunionfindobjectindex.Youwillneedtocomeupwitha
schemeforuniquelymapping2Dcoordinatesto1Dcoordinates.Werecommendwritingaprivatemethodwithasignaturealongthelinesofint
xyTo1D(int,int)thatperformsthisconversion.Youwillneedtoutilizethepercolationgridsizewhenwritingthismethod.Writingsuchaprivatemethod
(insteadofcopyingandpastingaconversionformulamultipletimesthroughoutyourcode)willgreatlyimprovethereadabilityandmaintainabilityofyour
code.Ingeneral,weencourageyoutowritesuchmoduleswhereverpossible.Directlytestthismethodusingthemain()functionofPercolation.
5. Writeaprivatemethodforvalidatingindices.Sinceeachmethodissupposedtothrowanexceptionforinvalidindices,youshouldwriteaprivate
methodwhichperformsthisvalidationprocess.
6. Writetheopen()methodandthePercolation()constructor.Theopen()methodshoulddothreethings.First,itshouldvalidatetheindicesofthesite
thatitreceives.Second,itshouldsomehowmarkthesiteasopen.Third,itshouldperformsomesequenceofWeightedQuickUnionUFoperationsthatlinks
thesiteinquestiontoitsopenneighbors.Theconstructorandinstancevariablesshouldfacilitatetheopen()method'sabilitytodoitsjob.
7. Testtheopen()methodandthePercolation()constructor.Thesetestsshouldbeinmain().Anexampleofasimpletestistocallopen(1,1)and
open(1,2),andthentoensurethatthetwocorrespondingentriesareconnected(using.connected()inWeightedQuickUnionUF).
8. Writethepercolates(),isOpen(),andisFull()methods.Theseshouldbeverysimplemethods.
9. Testyourcompleteimplementationusingthevisualizationclients.
10. WriteandtestthePercolationStatsclass.
ProgrammingTricksandCommonPitfalls
1. DonotwriteyourownUnionFinddatastructure.UseWeightedQuickUnionUFinstead.
2. YourPercolationclassshouldusetheWeightedQuickUnionUFclass.IfyousubmitwiththeUFclass,yourcodewillfailthetimingtests.
3. It'soktouseanextrarowand/orcolumntodealwiththe1basedindexingofthepercolationgrid.Thoughitisslightlyinefficient,it'sfinetouse
arraysorunionfindobjectsthatareslightlylargerthanstrictlynecessary.Doingthisresultsincleanercodeatthecostofslightlygreatermemoryusage.
4. Eachofthemethods(excepttheconstructor)inPercolationmustuseaconstantnumberofunionfindoperations.Ifyouhaveaforloopinsideof
oneofyourPercolationmethods,you'reprobablydoingitwrong.Don'tforgetaboutthevirtualtop/virtualbottomtrickdescribedinlecture.

http://coursera.cs.princeton.edu/algs4/checklists/percolation.html

3/3

You might also like