10WriteafilterTenPerLine.javathattakesasequenceofintegersbetween0and99andprints10integersperline,withcolumnsaligned.ThenwriteaprogramRandomIntSeqthattakestwocommand-lineargumentsMandNandoutputsNrandomintegersbetween0andM-1.TestyourprogramswiththecommandjavaRandomIntSeq200100|javaTenPerLine.
11WriteaprogramWordCount.javathatreadsintextfromstandardinputandprintsoutthenumberofwordsinthetext.Forthepurposeofthisexercise,awordisasequenceofnon-whitespacecharactersthatissurroundedbywhitespace.
12Writeaprogramthatreadsinlinesfromstandardinputwitheachlinecontaininganameandtwointegersandthenusesprintf()toprintatablewithacolumnofthenames,theintegers,andtheresultofdividingthefirstbythesecond,accuratetothreedecimalplaces.Youcoulduseaprogramlikethistotabulatebattingaveragesforbaseballplayersorgradesforstudents.
13Whichofthefollowingrequiresavingallthevaluesfromstandardinput(inanarray,say),andwhichcouldbeimplementedasafilterusingonlyafixednumberofvariables?
Foreach,theinputcomesfromstandardinputandconsistsofNrealnumbersbetween0and1.
∙Printthemaximumandminimumnumbers.
∙Printthekthsmallestvalue.
∙Printthesumofthesquaresofthenumbers.
∙PrinttheaverageoftheNnumbers.
∙Printthepercentageofnumbersgreaterthantheaverage.
∙PrinttheNnumbersinincreasingorder.
∙PrinttheNnumbersinrandomorder.
14Writeaprogramthatprintsatableofthemonthlypayments,remainingprincipal,andinterestpaidforaloan,takingthreenumbersascommand-linearguments:
thenumberofyears,theprincipal,andtheinterestrate(seeExercise1.2.24).
15WriteaprogramClosest.javathattakesthreecommand-lineargumentsx,y,z,readsfromstandardinputasequenceofpointcoordinates(xi,yi,zi),andprintsthecoordinatesofthepointclosestto(x,y,z).Recallthatthesquareofthedistancebetween(x,y,z)and(xi,yi,zi)is(x-xi)2+(y-yi)2+(z-zi)2.Forefficiency,donotuseMath.sqrt()orMath.pow().
16Giventhepositionsandmassesofasequenceofobjects,writeaprogrmtocomputetheircenter-of-massorcentroid.ThecentroidistheaveragepositionoftheNobjects,weightedbymsass.Ifthepositionsandmassesaregivenby(xi,yi,mi),thenthecentroid(x,y,m)isgivenby:
m=m1+m2+...+mN
x=(m1x1+...+mnxN)/m
y=(m1y1+...+mnyN)/m
WriteaprogramCentroid.javathatreadsinasequenceofpositionsandmasses(xi,yi,mi)fromstandardinputandprintsouttheircenterofmass(x,y,m).Hint:
modelyourprogramafterAverage.java.
17WriteaprogramSignalAnalyzer.javathatreadsinasequenceofrealnumbersbetween-1and1andprintsouttheiraveragemagnitude,averagepower,andthenumberofzerocrossings.Theaveragemagnitudeistheaverageoftheabsolutevaluesofthedatavalues.Theaveragepoweristheaverageofthesquaresofthedatavalues.Thenumberofzerocrossingsisthenumberoftimesadatavaluetransitionsfromastrictlynegativenumbertoastrictlypositivenumber,orviceversa.Thesethreestatisticsarewidelyusedtoanalyzedigitalsignals.
18WriteaprogramCheckerBoard.javathattakesacommand-lineargumentNandplotsanN-by-Ncheckerboardwithredandblacksquares.Colorthelowerleftsquarered.
19Writeaprogramthattakesascommand-lineargumentsanintegerNandadoublevaluep(between0and1),plotsNequallyspacedpointsofsizeonthecircumferenceofacircle,andthen,withprobabilitypforeachpairofpoints,drawsagraylineconnectingthem.
20Writecodetodrawhearts,spades,clubs,anddiamonds.Todrawaheart,drawadiamond,thenattachtwosemicirclestotheupperleftandupperrightsides.
21WriteaprogramRose.javathattakesacommand-lineargumentNandplotsarosewithNpetals(ifNisodd)or2Npetals(ifNiseven)byplottingthepolarcoordinates(r,θ)ofthefunctionr=sin(N×θ)forθrangingfrom0to2πradians.BelowisthedesiredoutputforN=4,7,and8.
22WriteaprogramBanner.javathattakesastringsfromthecommandlineanddisplayitinbannerstyleonthescreen,movingfromlefttorightandwrappingbacktothebeginningofthestringastheendisreached.Addasecondcommand-lineargumenttocontrolthespeed.
23ModifyPlayThatTune.javatotakeadditionalcommand-lineargumentsthatcontrolthevolume(multiplyeachsamplevaluebythevolume)andthetempo(multiplyeachnotesdurationbythetempo).
24Writeaprogramthattakesthenameofa.wavfileandaplaybackraterascommand-lineargumentsandplaysthefileatthegivenrate.First,useStdAudio.read()toreadthefileintoanarraya[].Ifr=1,justplaya[];otherwisecreateanewarrayb[]ofapproximatesizertimesa.length.Ifr<1,populateb[]bysamplingfromtheoriginal;ifr>1,populateb[]byinterpolatingfromtheoriginal.Thenplayb[].
25WriteprogramsthatusesStdDrawtocreateeachofthefollowingdesigns.
26
27WriteaprogramCircles.javathatdrawsfilledcirclesofrandomsizeatrandompositionsintheunitsquare,producingimageslikethosebelow.Yourprogramshouldtakefourcommand-linearguments:
thenumberofcircles,theprobabilitythateachcircleisblack,theminimumradius,andthemaximumradius.
CreativeExercises
28Visualizingaudio.ModifyPlayThatTune.javatosendthevaluesplayedtostandarddrawing,sothatyoucanwatchthesoundwavesastheyareplayed.Youwillhavetoexperimentwithplottingmultiplecurvesinthedrawingcanvastosynchronizethesoundandthepicture.
29Statisticalpolling.Whencollectingstatisticaldataforcertainpoliticalpolls,itisveryimportanttoobtainanunbiasedsampleofregisteredvoters.AssumethatyouhaveafilewithNregisteredvoters,oneperline.WriteafilterthatprintsoutarandomsampleofsizeM(seeProgram1.4.1).
30Terrainanalysis.Supposethataterrainisrepresentedbyatwo-dimensionalgridofelevationvalues(inmeters).Apeakisagridpointwhosefourneighboringcells(left,right,up,anddown)havestrictlylowerelevationvalues.WriteaprogramPeaks.javathatreadsaterrainfromstandardinputandthencomputesandprintsthenumberofpeaksintheterrain.
31Histogram.Supposethatthestandardinputstreamisasequenceofdoublevalues.WriteaprogramthattakesanintegerNandtwodoublevalueslandrfromthecommandlineandusesStdDrawtoplotahistogramofthecountofthenumbersinthestandardinputstreamthatfallineachoftheNintervalsdefinedbydividing(l,r)intoNequal-sizedintervals.
32Spirographs.WriteaprogramSpirograph.javathattakesthreecommand-lineargumentsR,r,andaanddrawstheresultingspirograph.Aspirograph(technically,anepicycloid)isacurveformedbyrollingacircleofradiusraroundalargerfixedcircleorradiusR.Ifthepenoffsetfromthecenteroftherollingcircleis(r+a),thentheequationoftheresultingcurveattimetisgivenby
x(t)=(R+r)*cos(t)-(r+a)*cos(((R+r)/r)*t)
y(t)=(R+r)*sin(t)-(r+a)*sin(((R+r)/r)*t)
Suchcurveswerepopularizedbyabest-sellingtoythatcontainsdiscswithgearteethontheedgesandsmallholesthatyoucouldputapenintotracespirographs.
Foradramatic3deffect,drawacircularimage,e.g.,earth.gifinsteadofadot,andshowitrotatingovertime.Here'sapictureoftheresultingspirographwhenR=180,r=40,anda=15.
33Clock.WriteaprogramClock.javathatdisplaysananimation