c# display pdf in browser : Add page number to pdf online Library SDK class asp.net .net azure ajax python-programming-an-introduction-to-computer-science15-part376

9.3. TOP-DOWNDESIGN
143
9.3.4 DesigningsimNGames
Nowthatwearegettingsomeexperiencewiththetop-downdesigntechnique,wearereadytotryourhandat
therealproblem,simNGames.Thisonerequiresabitmorethought.Thebasicideaistosimulatengames
andkeeptrackofhowmanywinsthereareforeachplayer.Well,“simulatengames”soundslikeacounted
loop,andtrackingwinssoundslikethejobforacoupleofaccumulators.Usingourfamiliarpatterns,wecan
piecetogetheranalgorithm.
Initialize winsA A and d winsB to 0
loop n times
simulate a a game
if playerA A wins
Add one e to o winsA
else
Add one e to o winsB
It
'
saprettyroughdesign,butthensowasourtop-levelalgorithm. We
'
llfillinthedetailsbyturningitinto
Pythoncode.
Remember,wealreadyhavethesignatureforourfunction.
def simNGames(n, , probA, , probB):
# Simulates s n n games and returns winsA and d winsB
We
'
lladdtothisbyinitializingthetwoaccumulatorvariablesandaddingthecountedloopheading.
def simNGames(n, , probA, , probB):
# Simulates s n n games and returns winsA and d winsB
winsA = 0
winsB = 0
for i in range(n):
Thenextstepinthealgorithmcallsforsimulatingagameofracquetball. I
'
mnotquitesurehowtodo
that,soasusual,I
'
llputoffthedetails.Let
'
sjustassumethere
'
safunctioncalledsimOneGametotakecare
ofthis.
Weneedtofigureoutwhattheinterfaceforthisfunctionwillbe. Theinputsforthefunctionseem
straightforward.Inordertoaccuratelysimulateagame,weneedtoknowwhattheprobabilitiesareforeach
player.Butwhatshouldtheoutputbe?Inthenextstepofthealgorithm,weneedtoknowwhowonthegame.
Howdoyouknowwhowon?Generally,youlookatthefinalscore.
Let
'
shavesimOneGamereturnthefinalscoresforthetwoplayers. Wecanupdateourstructurechart
toreflectthesedecisions. TheresultisshowninFigure9.2. Translatingthisstructureintocodeyieldsthis
nearlycompletedfunction:
def simNGames(n, , probA, , probB):
# Simulates s n n games and returns winsA and d winsB
winsA = 0
winsB = 0
for i in range(n):
scoreA, scoreB B = simOneGame(probA, probB)
Finally,weneedtocheckthescorestoseewhowonandupdatetheappropriateaccumulator.Hereisthe
result.
def simNGames(n, , probA, , probB):
winsA = winsB B = = 0
for i in range(n):
scoreA, scoreB B = simOneGame(probA, probB)
if scoreA A > > scoreB:
winsA = = winsA A + 1
Add page number to pdf online - insert pages into PDF file in C#.net, ASP.NET, MVC, Ajax, WinForms, WPF
Guide C# Users to Insert (Empty) PDF Page or Pages from a Supported File Format
adding page numbers in pdf file; add a page to a pdf file
Add page number to pdf online - VB.NET PDF Page Insert Library: insert pages into PDF file in vb.net, ASP.NET, MVC, Ajax, WinForms, WPF
Easy to Use VB.NET APIs to Add a New Blank Page to PDF Document
adding page numbers to pdf files; add page to pdf online
144
CHAPTER9. SIMULATIONANDDESIGN
probA
probB
n
probA
probB
n
winsA
winsB
winsA
winsB
simOneGame
probA
probB
scoreA
scoreB
main
printIntro
getInputs
simNGames
printSummary
Figure9.2:Level2structurechartforracquetballsimulation.
else:
winsB = = winsB B + 1
return winsA, , winsB
9.3.5 Third-LevelDesign
Everythingseemstobecomingtogethernicely. Let
'
skeepworkingonthegutsofthesimulation. The
nextobviouspointofattackissimOneGame. Here
'
swhereweactuallyhavetocodeupthelogicofthe
racquetballrules. Playerskeepdoingralliesuntilthegameisover. . Thatsuggestssomekindofindefinite
loopstructure;wedon
'
tknowhowmanyralliesitwilltakebeforeoneoftheplayersgetsto15.Theloopjust
keepsgoinguntilthegameisover.
Alongtheway,weneedtokeeptrackofthescore(s),andwealsoneedtoknowwhoiscurrentlyserving.
Thescoreswillprobablyjustbeacoupleofint-valuedaccumulators,buthowdowekeeptrackofwho
'
s
serving? It
'
seitherplayerAorplayerB.Oneapproachistouseastringvariablethatstoreseither"A"or
"B".It
'
salsoanaccumulatorofsorts,buttoupdateitsvalue,wejustswitchitfromonevaluetotheother.
That
'
senoughanalysistoputtogetheraroughalgorithm.Let
'
strythis:
Initialize scores s to o 0
Set serving to o "A"
Loop while game e is s not over:
Simulate one e serve e of whichever player is s serving
update the e status s of the game
Return scores
It
'
sastart,atleast.Clearlythere
'
sstillsomeworktobedoneonthisone.
Wecanquicklyfillinthefirstcouplestepsofthealgorithmtogetthefollowing.
def simOneGame(probA, , probB):
scoreA = 0
scoreB = 0
serving = = "A"
while <condition>:
Thequestionatthispointisexactlywhattheconditionwillbe. Weneedtokeeploopingaslongasthe
gameisnotover. Weshouldbeabletotellifthegameisoverbylookingatthescores. . Wediscusseda
C# PDF insert text Library: insert text into PDF content in C#.net
pageIndex, The page index of the PDF page that will be 0
add page to pdf without acrobat; adding page numbers to pdf documents
C# PDF File Split Library: Split, seperate PDF into multiple files
If your page number is set as 1, then the two output PDF files will contains the first page and the later three pages Add necessary references:
add page numbers pdf file; add page numbers to pdf in reader
9.3. TOP-DOWNDESIGN
145
numberofpossibilitiesforthisconditioninthepreviouschapter,someofwhichwerefairlycomplex.Let
'
s
hidethedetailsinanotherfunction,gameOver,thatlooksatthescoresandreturnstrue(1)ifthegameis
over,andfalse(0)ifitisnot.Thatgetsusontotherestoftheloopfornow.
Figure9.3showsthestructurechartwithournewfunction.ThecodeforsimOneGamenowlookslike
this:
def simOneGame(probA, , probB):
scoreA = 0
scoreB = 0
serving = = "A"
while not t gameOver(scoreA, , scoreB):
probA
probB
n
probA
probB
n
winsA
winsB
winsA
winsB
simOneGame
probA
probB
scoreA
scoreB
main
scoreA
scoreB
true|false
printIntro
getInputs
simNGames
printSummary
gameOver
Figure9.3:Level3structurechartforracquetballsimulation.
Insidetheloop,weneedtodoasingleserve.Remember,wearegoingtocomparearandomnumbertoa
probabilityinordertodetermineiftheserverwinsthepoint(random() < prob).Thecorrectprobability
touseisdeterminedbythevalueofserving.Wewillneedadecisionbasedonthisvalue.IfAisserving,
thenweneedtouseA
'
sprobability,and,basedontheresultoftheserve,updateeitherA
'
sscoreorchange
theservicetoB.Hereisthecode:
if serving == = "A":
if random() ) < < probA:
# A wins the serve
scoreA = = scoreA + 1
else:
# A loses the serve
serving = = "B"
Ofcourse,ifAisnotserving,weneedtodothesamething,onlyforB.Wejustneedtoattachamirror
imageelseclause.
if serving == = "A":
if random() ) < < probA:
# A wins the serve
scoreA = = scoreA + 1
VB.NET PDF File Split Library: Split, seperate PDF into multiple
can split target multi-page PDF document file to one-page PDF files or PDF file to smaller PDF documents by every given number of pages Add necessary references
add pages to pdf reader; add page number to pdf
C# PDF Text Search Library: search text inside PDF file in C#.net
Add necessary references: Description: Search specified string from all the PDF pages. eg: The first page is 0. 0
add and delete pages in pdf online; add page number to pdf in preview
146
CHAPTER9. SIMULATIONANDDESIGN
else:
# A loses serve
serving = = "B"
else:
if random() ) < < probB:
# B wins the serve
scoreB = = scoreB + 1
else:
# B loses the serve
serving = = "A"
Thatprettymuchcompletesthefunction. Itgotabitcomplicated,butseemstoreflecttherulesofthe
simulationastheywerelaidout.Puttingthefunctiontogether,hereistheresult.
def simOneGame(probA, , probB):
scoreA = 0
scoreB = 0
serving = = "A"
while gameNotOver(scoreA, , scoreB):
if serving g == = "A":
if random() < probA:
scoreA = = scoreA + 1
else:
serving = = "B"
else:
if random() < probB:
scoreB = = scoreB + 1
else:
serving = = "A"
return scoreA, , scoreB
9.3.6 FinishingUp
Whew!Wehavejustonemoretroublesomefunctionleft,gameOver.Hereiswhatweknowaboutitsofar.
def gameOver(a,b):
# a and b b represent t scores for a racquetball l game
# RETURNS S true e if the game is over, false e otherwise.
Accordingtotherulesforoursimulation,agameisoverwheneitherplayerreachesatotalof15. Wecan
checkthiswithasimpleBooleancondition.
def gameOver(a,b):
# a and b b represent t scores for a racquetball l game
# RETURNS S true e if the game is over, false e otherwise.
return a==15 5 or r b==15
NoticehowthisfunctiondirectlycomputesandreturnstheBooleanresultallinonestep.
We
'
vedoneit! ExceptforprintSummary,theprogramiscomplete. Let
'
sfillinthemissingdetails
andcallitawrap.Hereisthecompleteprogramfromstarttofinish:
# rball.py
from random import t random
def main():
printIntro()
probA, probB, , n n = getInputs()
winsA, winsB B = = simNGames(n, probA, probB)
printSummary(winsA, winsB)
C# PDF File & Page Process Library SDK for C#.net, ASP.NET, MVC
Highlight Text. Add Text. Add Text Box. Drawing Markups. PDF VB.NET merge PDF files, VB.NET view PDF online, VB.NET Please note that, PDF page number starts from
adding page numbers to a pdf file; adding pages to a pdf document in preview
C# PDF delete text Library: delete, remove text from PDF file in
Add necessary references: RasterEdge.Imaging.Basic.dll. matchString, The string wil be deleted from PDF file, -. 0
add page break to pdf; add pages to pdf acrobat
9.3. TOP-DOWNDESIGN
147
def printIntro():
print "This s program m simulates a game of racquetball l between n two"
print 'players s called d "A" and "B".
The abilities s of f each player is'
print "indicated d by y a probability (a number r between n 0 and 1) that"
print "the e player r wins the point when serving. . Player r A always"
print "has s the e first serve."
def getInputs():
# Returns s the e three simulation parameters
a = input("What t is s the prob. player A wins s a a serve? ")
b = input("What t is s the prob. player B wins s a a serve? ")
n = input("How w many y games to simulate? ")
return a, , b, , n
def simNGames(n, , probA, , probB):
# Simulates s n n games of racquetball between n players s whose
#
abilities are e represented by the probability y of f winning a serve.
# RETURNS S number r of wins for A and B
winsA = winsB B = = 0
for i in range(n):
scoreA, scoreB B = simOneGame(probA, probB)
if scoreA A > > scoreB:
winsA = = winsA A + 1
else:
winsB = = winsB B + 1
return winsA, , winsB
def simOneGame(probA, , probB):
# Simulates s a a single game or racquetball between n players s whose
#
abilities are e represented by the probability y of f winning a serve.
# RETURNS S final l scores for A and B
serving = = "A"
scoreA = 0
scoreB = 0
while not t gameOver(scoreA, , scoreB):
if serving g == = "A":
if random() < probA:
scoreA = = scoreA + 1
else:
serving = = "B"
else:
if random() < probB:
scoreB = = scoreB + 1
else:
serving = = "A"
return scoreA, , scoreB
def gameOver(a, , b):
# a and b represent scores for a racquetball l game
# RETURNS S true e if the game is over, false e otherwise.
return a==15 5 or r b==15
def printSummary(winsA, , winsB):
# Prints a a summary y of wins for each player.
C# PDF Text Highlight Library: add, delete, update PDF text
200F); annot.EndPoint = new PointF(300F, 400F); // add annotation to The string wil be highlighted from PDF file, 0
add page numbers to pdf document in preview; add page pdf reader
C# PDF Page Delete Library: remove PDF pages in C#.net, ASP.NET
Add necessary references: RasterEdge.Imaging.Basic.dll. 0
add page numbers to pdf document; add page to pdf
148
CHAPTER9. SIMULATIONANDDESIGN
n = winsA A + + winsB
print "\nGames s simulated:", , n
print "Wins s for r A: %d (%0.1f%%)" % (winsA, , float(winsA)/n*100)
print "Wins s for r B: %d (%0.1f%%)" % (winsB, , float(winsB)/n*100)
if __name__ == = '__main__': : main()
YoumighttakenoticeofthestringformattinginprintSummary.Sinceapercentsignnormallymarksthe
beginningofaslotspecifier,togetanormalpercentsignattheend,Ihadtouseadoublepercent%%.
9.3.7 SummaryoftheDesignProcess
Youhavejustseenanexampleoftop-downdesigninaction.Nowyoucanreallyseewhyit
'
scalledtop-down
design. Westartedatthehighestlevelofourstructurechartandworkedourwaydown. . Ateachlevel,we
beganwithageneralalgorithmandthengraduallyrefineditintoprecisecode. Thisapproachissometimes
calledstep-wiserefinement.Thewholeprocesscanbesummarizedinfoursteps:
1. Expressthealgorithmasaseriesofsmallerproblems.
2. Developaninterfaceforeachofthesmallproblems.
3. Detailthealgorithmbyexpressingitintermsofitsinterfaceswiththesmallerproblems.
4. Repeattheprocessforeachsmallerproblem.
Top-downdesignisaninvaluabletoolfordevelopingcomplexalgorithms. Theprocessmayseemeasy,
sinceI
'
vewalkedyouthroughitstep-by-step.Whenyoufirsttryitoutforyourself,though,thingsprobably
won
'
tgoquitesosmoothly.Staywithit—themoreyoudoit,theeasieritwillget. Initially,youmaythink
writingallofthosefunctionsisalotoftrouble.Thetruthis,developinganysophisticatedsystemisvirtually
impossiblewithoutamodularapproach. Keepatit,andsoonexpressingyourownprogramsintermsof
cooperatingfunctionswillbecomesecondnature.
9.4 Bottom-UpImplementation
Nowthatwe
'
vegotaprograminhand,yourinclinationmightbetorunoff,typethewholethingin,andgive
itatry.Ifyoudothat,theresultwillprobablybedisappointmentandfrustration.Eventhoughwehavebeen
verycarefulinourdesign,thereisnoguaranteethatwehaven
'
tintroducedsomesillyerrors.Evenifthecode
isflawless,you
'
llprobablymakesomemistakeswhenyouenterit.Justasdesigningaprogramonepieceat
atimeiseasierthantryingtotacklethewholeproblematonce,implementationisbestapproachedinsmall
doses.
9.4.1 UnitTesting
Agoodwaytoapproachtheimplementationofamodestsizeprogramistostartatthelowerlevelsofthe
structurechartandworkyourwayup,testingeachcomponentasyoucompleteit. Lookingbackatthe
structurechartforoursimulation,wecouldstartwiththegameOverfunction. Oncethisfunctionistyped
intoamodulefile,wecanimmediatelyimportthefileandtestit.Hereisasamplesessiontestingoutjustthis
function.
>>> import rball
>>> rball1.gameOver(0,0)
0
>>> rball1.gameOver(5,10)
0
>>> rball1.gameOver(15,3)
1
9.4. BOTTOM-UPIMPLEMENTATION
149
>>> rball1.gameOver(3,15)
1
Ihaveselectedtestdatathatexercisealltheimportantcasesforthefunction. Thefirsttimeitiscalled,the
scorewillbe0to0. Thefunctioncorrectlyrespondswith0(false);thegameisnotover. . Asthegame
progresses,thefunctionwillbecalledwithintermediatescores.Thesecondexampleshowsthatthefunction
againrespondedthatthegameisstillinprogress. Thelasttwoexamplesshowthatthefunctioncorrectly
identifiesthatthegameisoverwheneitherplayerreaches15.
HavingconfidencethatgameOverisfunctioningcorrectly,nowwecangobackandimplementthe
simOneGamefunction. Thisfunctionhassomeprobabilisticbehavior,soI
'
mnotsureexactlywhatthe
outputwillbe.Thebestwecandointestingitistoseethatitbehavesreasonably.Hereisasamplesession.
>>> import rball
>>> rball1.simOneGame(.5,.5)
(13, 15)
>>> rball1.simOneGame(.5,.5)
(15, 11)
>>> rball1.simOneGame(.3,.3)
(15, 11)
>>> rball1.simOneGame(.3,.3)
(11, 15)
>>> rball1.simOneGame(.4,.9)
(4, 15)
>>> rball1.simOneGame(.4,.9)
(1, 15)
>>> rball1.simOneGame(.9,.4)
(15, 3)
>>> rball1.simOneGame(.9,.4)
(15, 0)
>>> rball1.simOneGame(.4,.6)
(9, 15)
>>> rball1.simOneGame(.4,.6)
(6, 15)
Noticethatwhentheprobabilitiesareequal,thescoresareclose.Whentheprobabilitiesarefartherapart,the
gameisarout.Thatsquareswithhowwethinkthisfunctionshouldbehave.
Wecancontinuethispiecewiseimplementation,testingouteachcomponentasweadditintothecode.
Softwareengineerscallthisprocessunittesting. Testingeachfunctionindependentlymakesiteasierto
spoterrors.Bythetimeyougetaroundtotestingtheentireprogram,chancesarethateverythingwillwork
smoothly.
Separatingconcernsthroughamodulardesignmakesitpossibletodesignsophisticatedprograms.Sep-
aratingconcernsthroughunittestingmakesitpossibletoimplementanddebugsophisticatedprograms.Try
thesetechniquesforyourself,andyou
'
llseethatyouaregettingyourprogramsworkingwithlessoverall
effortandfarlessfrustration.
9.4.2 SimulationResults
Finally,wecantakealookatDennyDibblebit
'
squestion.Isitthenatureofracquetballthatsmalldifferences
inabilityleadtolargedifferencesintheoutcome? SupposeDennywinsabout60%ofhisservesandhis
opponentis5%better. HowoftenshouldDennywinthegame? Here
'
sanexamplerunwhereDenny
'
s
opponentalwaysservesfirst.
This program simulates s a a game of racquetball between n two
players called d "A" " and "B".
The abilities of f each h player is
indicated by a a probability y (a number between 0 0 and d 1) that
the player wins s the e point when serving. Player r A A always
150
CHAPTER9. SIMULATIONANDDESIGN
has the first t serve.
What is the prob. . player r A wins a serve? .65
What is the prob. . player r B wins a serve? .6
How many games s to o simulate? 5000
Games simulated: : 5000
Wins for A: 3360 0 (67.2%)
Wins for B: 1640 0 (32.8%)
Eventhoughthereisonlyasmalldifferenceinability,Dennyshouldwinonlyaboutoneinthreegames.His
chancesofwinningathree-orfive-gamematchareprettyslim.ApparentlyDennyiswinninghisshare.He
shouldskiptheshrinkandworkharderonhisgame.
Speakingofmatches,expandingthisprogramtocomputetheprobabilityofwinningmulti-gamematches
wouldbeagreatexercise.Whydon
'
tyougiveitatry?
9.5 OtherDesignTechniques
Top-downdesignisaverypowerfultechniqueforprogramdesign,butitisnottheonlywaytogoabout
creatingaprogram.Sometimesyoumaygetstuckatastepandnotknowhowtogoaboutrefiningit.Orthe
originalspecificationmightbesocomplicatedthatrefiningitlevel-by-levelisjusttoodaunting.
9.5.1 PrototypingandSpiralDevelopment
Anotherapproachtodesignistostartwithasimpleversionofaprogramorprogramcomponentandthen
trytograduallyaddfeaturesuntilitmeetsthefullspecification. Theinitialstripped-downversioniscalled
aprototype. Prototypingoftenleadstoasortofspiraldevelopmentprocess. . Ratherthantakingtheentire
problemandproceedingthroughspecification,design,implementationandtesting,wefirstdesign,implement
andtestaprototype.Thennewfeaturesaredesigned,implementedandtested. Wemakemanymini-cycles
throughthedevelopmentprocessastheprototypeisincrementallyexpandedintothefinalprogram.
Asanexample,considerhowwemighthaveapproachedtheracquetballsimulation.Theveryessenceof
theproblemissimulatingagameofracquetball.WemighthavestartedwithjustthesimOneGamefunction.
Simplifyingevenfurther,ourprototypecouldassumethateachplayerhasa50-50chanceofwinningany
givenpointandjustplayaseriesof30rallies. Thatleavesthecruxoftheproblem,whichishandlingthe
awardingofpointsandchangeofservice.Hereisanexampleprototype:
from random import t random
def simOneGame():
scoreA = 0
scoreB = 0
serving = = "A"
for i in range(30):
if serving g == = "A":
if random() < .5:
scoreA = scoreA + 1
else:
serving = "B"
else:
if random() < .5:
scoreB = scoreB + 1
else:
serving = "A"
print scoreA, , scoreB
9.5. OTHERDESIGNTECHNIQUES
151
if __name__ == = '__main__': : simOneGame()
YoucanseethatIhaveaddedaprintstatementatthebottomoftheloop.Printingoutthescoresaswego
alongallowsustoseethattheprototypeisplayingagame.Hereissomeexampleoutput.
1 0
1 0
1 0
2 0
2 0
2 1
2 1
3 1
3 1
3 1
3 1
3 2
...
7 6
7 7
7 8
It
'
sisnotpretty,butitshowsthatwehavegottenthescoringandchangeofserviceworking.
Wecouldthenworkonaugmentingtheprograminphases.Here
'
saprojectplan.
Phase1 Initialprototype. Play30rallieswheretheserveralwayshasa50%chanceofwinning. Printout
thescoresaftereachrally.
Phase2 Addtwoparameterstorepresentdifferentprobabilitiesforthetwoplayers.
Phase3 Playthegameuntiloneoftheplayersreaches15points.Atthispoint,wehaveaworkingsimulation
ofasinglegame.
Phase4 Expandtoplaymultiplegames.Theoutputisthecountofgameswonbyeachplayer.
Phase5 Buildthecompleteprogram.Addinteractiveinputsandanicelyformattedreportoftheresults.
Spiraldevelopmentisparticularlyusefulwhendealingwithneworunfamiliarfeaturesortechnologies.
It
'
shelpfulto“getyourhands dirty”withaquickprototypejusttoseewhatyoucando. . Asanovice
programmer,everythingmayseemnewtoyou,soprototypingmightproveuseful. Iffull-blowntop-down
designdoesnotseemtobeworkingforyou,trysomespiraldevelopment.
9.5.2 TheArtofDesign
Itisimportanttonotethatspiraldevelopmentisnotanalternativetotop-downdesign.Rather,theyarecom-
plementaryapproaches.Whendesigningtheprototype,youwillstillusetop-downtechniques.InChapter12,
youwillseeyetanotherapproachcalledobject-orienteddesign.
Thereisno“onetrueway”ofdesign. Thetruthisthatgooddesignisasmuchacreativeprocessasa
science.Designscanbemeticulouslyanalyzedafterthefact,buttherearenohardandfastrulesforproducing
adesign.Thebestsoftwaredesignersseemtoemployavarietyoftechniques.Youcanlearnabouttechniques
byreadingbookslikethisone,butbookscan
'
tteachhowandwhentoapplythem.Thatyouhavetolearnfor
yourselfthroughexperience.Indesignasinalmostanything,thekeytosuccessispractice.
152
CHAPTER9. SIMULATIONANDDESIGN
9.6 Exercises
1. Drawthetoplevelsofastructurechartforaprogramhavingthefollowingmainfunction.
def main():
printIntro()
length, width = getDimensions()
amtNeeded = computeAmount(length,width)
printReport(length, width, , amtNeeded)
2. Writeanexpressionusingeitherrandomorrandrangetocalculatethefollowing.
Arandomintintherange0–10
Arandomfloatintherange-0.5–0.5
Arandomnumberrepresentingtherollofasix-sideddie
Arandomnumberrepresentingthesumresultingfromrollingtwosix-sideddice
Arandomfloatintherange-10.0–10.0
3. Revisetheracquetballsimulationsothatitkeepstrackofresultsforbestofngamematches.
4. Revisetheracquetballsimulationtotakeshutoutsintoaccount.Yourupdatedversionshouldreportfor
bothplayersthenumberofwins,percentageofwins,numberofshutouts,andpercentageofwinsthat
areshutouts.
5. Designandimplementasimulationofthegameofvolleyball. . Normalvolleyballisplayedlikerac-
quetball,inthatateamcanonlyscorepointswhenitisserving. Gamesareplayedto15,butmustbe
wonbyatleasttwopoints.
6. Collegevolleyballisnowplayedusingrallyscoring. . Inthis s system,theteamthatwinsarallyis
awardedapoint,eveniftheywerenottheservingteam. Gamesareplayedtoascoreof21. . Design
andimplementasimulationofvolleyballusingrallyscoring.
7. Designandimplementasystemthatcomparesregularvolleyballgamestothoseusingrallyscoring.
Yourprogramshouldbeabletoinvestigatewhetherrallyscoringmagnifies,reduces,orhasnoeffect
ontherelativeadvantageenjoyedbythebetterteam.
8. Designandimplementasimulationofsomeotherracquetsport(e.g.tennisortabletennis).
9. Crapsisadicegameplayedatmanycasinos. . Aplayerrollsapairofnormalsix-sideddice. Ifthe
initialrollis2,3or12,theplayerloses. Iftherollis7or11,theplayerwins. Anyotherinitialroll
causestheplayerto“rollforpoint.”Thatis,theplayerkeepsrollingthediceuntileitherrollinga7or
re-rollingthevalueoftheinitialroll.Iftheplayerre-rollstheinitialvaluebeforerollinga7,it
'
sawin.
Rollinga7firstisaloss.
Writeaprogramtosimulatemultiplegamesofcrapsandestimatetheprobabilitythattheplayerwins.
Forexample,iftheplayerwins249outof500games,thentheestimatedprobabilityofwinningis
249
500
0
498
10. Blackjack(twenty-one)isacasinogameplayedwithcards. . Thegoalofthegametodrawcardsthat
totalascloseto21pointsaspossiblewithoutgoingover.Allfacecardscountas10points,acescount
as1or11,andallothercardscounttheirnumericvalue.
Thegameisplayedagainstadealer. Theplayertriestogetcloserto21(withoutgoingover)than
thedealer. Ifthedealerbusts(goesover21)theplayerautomaticallywins(providedtheplayerhad
notalreadybusted). Thedealermustalwaystakecardsaccordingtoafixedsetofrules. . Thedealer
takescardsuntilheorsheachievesatotalofatleast17.Ifthedealer
'
shandcontainsanace,itwillbe
countedas11whenthatresultsinatotalbetween17and21inclusive;otherwise,theaceiscountedas
1.
Documents you may be interested
Documents you may be interested