January 16, 1992 Herbefi L. Dershem Department

advertisement
DEFENSE AOVANCED RESEARCH FROJECTS
AGENCY
37OI NORTH FAIRFAX DRIVE
ARLTNGTON, VA 2220.3-1-714
January16,1992
Herbefi L. Dershem
Departmentof ComputerScience
Hope College
Holland, MI 49423
Subje.t : B.a..^.PrcFcre!
Use Ada, l,aboratories,and Visualizationin the Teaching
of Data Shuctu€s
-of
LOSf, Z)
sIJTo,BAA9I-I8
Dear Mr. Dershem:
,o]:"j:r:prr"l ,ubmittod
inresponse
to tbecommerce
Business
Daity
I3:,:1T'.t:.:l.T:lT1T
lssueor to Jutyl99l tor a DARpA_sDonsored
program
-BAA
Engineering
andAda,DARPA/CMO
9l-i8.
of CuriculumDevglopment
in Softwaro
Yourproposalwasevaluated
in accordance
with thecdteriasetfofih in theannouncement,
andis
d.,_",yined-to.be
a potential
candidate
for
funding.
Since
it
is
not
anticipeted
that
T:.:f.::i:r4
*u, * sutticienrto suppodall suchproposals,
we
are
unable
to
be
more
specific
i::.,-r::
li":: tlme.except
ar rneprcseot
to saythatshouldyourproposalthenbe selectedfor funding,youwill
becontxcted
by our ContmctsMamge[FntOffic€.
Thankyoufor yourparticipation
in thisprocuement.your offortsin expressing
theideasandcon_
ceptsof yourproposalarcapprcciated.
Weanticipate
thepublicationofi new,ida Under$aduate
CurdculumBroadAgencyAnnouncement
by theendof February.DARPAwishesto encourage
yourpsrticipationin '$is anddl fuiurcprogruns
Dr. JohnF. Kramer
ProgramManager
Softwareand Intetligent SystemsTechnologyOffice
cc: JamesM. Gentile
/
t
- c
A. CoYerPage
91-18
BroadAgencyAnnouncement
ENGINEERINGAND ADA
IN SOFT'WARE
CURRICT'L'M DEVEITOPMENT
CalegoryI Proposal
ProposalTitle: Useof Ada, hboratories, andvisualizationin theTeachingof DataStructurcs
andDiscreteMathematics
TechnicalPointof Contacc
HerbeitL. Dershem
Departmentof Comput€rSci€nce
HopeCollege
Holand' MI 49423
(616)39+7508
dershem@cs.hop€.edu
AdministrativePointof Contact: JamesM. Gentile
Deanfor the NaturalScieoc€s
HoP€College
Ilolland, MI 49423
(6rq 394'7714
a"\
C{hb HopecoLLEGE
L CIENCES
D E A NF O RN A T U R A S
September23, 1991
BAA #91-18
DARPA./SISTO
3701 North Fairfax Drive
Arlington, VA 22203-17
14
TO WHOM IT MAY CONCERN:
It is with significantenthusiasmand excitementthat I endorsethe ideasand
conceptspresentedby the Department of Computer Scienceat Hope Collegein
this proposalentitled "Use of Ada, I-aboratories,and Visualizationin the Teaching
of Data Structuresand DiscreteMathematics."
The programdescdbedin this proposal is timely and innovative. It will allow
a firm
studentsto more easilybddge perceiveddisciplinarygapsand it establishes
studfng
mathematics
and
computer
foundationoI connectedness
for students
in scienceand mathematicsis crucial
science.The propertyof connectedness
becauseit prcvidesthe learnerwith a tangiblemeansof knowing. The proposed
cu[icular endeavoris welcomingof sludentsand it is understandingof the
variancesin backgroundsthat studentsbring v/ith them from high school. It is
designedto meet students'Vhere they are" and help studentsto achievetheir
fullestpotentialof unde$tanding.
Hope Collegeis committedto support this program in everyway. My office will
work with ProfessorDershemin a coordinatedfashion to insureprcgrammatic
success.
we are thanKul for the opportunityto submit this proposaland \re look forwald
to developinga vital programthat will provide studentswith the tools necessary
for future successin computerscience.
Sincerelv.
;h*'t
/
L--/
,Aanes M.
I)ean fot the NaturalSciences
and
The Kenneth G. Herrick Professorof Biologr
JMG:b
HOLLAND,MICHTCAN49423-369A/ 616 394 7714
B. Descriptionof the Project
Summaryof Prcject
of a rew coursein DataStucturesthatincludesthe
Thepropos€dprojectis for thedevelopment
following features:
of theconc€ptof AbstractDataTypes.
1. The useof Ada to aid in the development
wherestudentswould meetin a laboratorys€ttingorc€ a weekto
2. A taboratorycomponent
in datastructues.
carry out expedments
for bothclas$oomdemonstration
3, Theuseof algorithmvisualizationandanimationtechniques
atld laboratoryactivities.
topicsinlo thecourse'includinggraphtheoryand
4. The inlegrationof discreiemathematics
recurenc€rclations.
CurrentSituation
Hopecollegeis a four-yearliberalartsinstitutoowith enrollmentofapproximately2,500. The
a comiuterscienc€depanmentsince1974. Thedepartment
Fesendyconsilts
cotiegetras-traa
of four full-timefacultynembers,threeof whomholdPh.D.degrcesin Compuierscience.The
il majorsin 1991and will gnduatea similarnumberin 19921
delartmentgraduat€d
The data structurcscourseat Hope Collegeis closelybasedon the CS7 courseof ACM
Curriculum78 Ul andCO2cou$e of the ACM Liberalkts Curriculum[1U. It is taker by
ComputerSciencrmajolsin the sophomoreyear, with Induction !o Comput'erScienc€and
hasbeentaughtwith
ComputerSciencetr asprerequisiteclufses. Since1985,datastructures
Modula2 astheprimaryprogratnmingtanguage.Prior !o thatPascalwasus€d. Beginningin
1990,the compuiu sciin-ceaepartnentUegana cunicularprogramthat introducesthe topics
commonlyinciudedin a discreteshucturescourseinto the first four coursesof the computer
sciencecurdculum,oneof whichis thedatastructwescourse.T'llediscretestructuescouse'
which was taught within the mathematicsdepartment,n'as cons€quertlyeliminat€das a
requirementfor the computersciencemajor'
Activities
ProPosed
Theproposedprojectwouldseekto developmaterialsto suppona cousein datashucturesthat
topicsinto the
language,integraledisctetemathematics
*ould oseAdi as the implementation
cou$e, and provide laboratoriesthat would engagethe studentsin experimentalwork and
algorithmvisualization-TheProjectDircctorwouldproduce,asa lesultof this Foject, course
m;terialsincludingsy abus,a lab manual,Ada softwarcus€din supportof thelaboratory,and
of the course.
comPonent
handoutssupportilgthediscretemathematics
It is proposedthat the courseard laboratorydesignbe completedand supportingsoftware
*ritteo duringthe sumruerof 1992,tlnt thecoursebe taughtandwdtten laboratoryexercises
of 1993,andthat the filished lab manualard a paper
be producedduringtheSpringSemester
be wdtter duringthe summerof 1993.
describingthe resultsof this curriculardevelopment
,
TechnicalApproachandRatiorEle
l" Introduction of Ada as the primary languagein a Data Structur€scours€.
The useof Ada in the datastructurescouse hasbe€npioneer€dby Feldman[9] and more
of Ada as oudinedin [10] include the
rec€ntlyadvocatedby Silver [13]. The advantages
following:
by the ability !o return any structurcas tlle resultof a
l. Dataabstractionis enhanc€d
function.
2. Packagesallow for the implementationof ADTS along with the scparationof
specificationfrom implementation.
the ability to implementencapsuLation.
3. Pdvatetyp€senhance
4. Genedcsenablethe studentsto work at an higher level of abstractionin the
constuctionof ADTS.
5. Exc€ptionhandlingcanbe includ€das an int€gralpart of the ADT.
In addition,aneadyexposureio Ada in theComputerSciencecurriculummakesthat language
availableasa tool in all laterc.urses. In particular,Ada is aheadyusedasa primarylanguage
andconcurentsystemscourses'and its usein datastructures
in the programminglanguages
wouldieducetheamountoi timeneededin theselater cnurses!o familiarizethe studentswith
Ada, Furthermore,studentswouldbe morclikely to chooseAda in later courseswherethey
havea choiceof whichlarguageto use.
2. Introduction of a liaboratorycomponedinto tie data structur€scou|se'
A significantamountof attentionhasbeengivenin recentcomputelsciencecurriculumstudies
to G introductionof laboratoryexperienc€s
Bl [14]' At gope College,we havealreadybegun
effortsto inFoiluc€laloratoriesinto ttrefust two coursesin the curiculum, that is, thosethat
of thoseimplementations
!o thedatastructuescou$e. Basedon the success
arc prerequisites
of theACM Curriculumcommitte€'we propor the ext€trsionof the
and-therecommendations
labontory approachto thedatastlucturcscourse.
4
The presentdatastructurescoursemeetsfor tirce hoursof lectureper week. The pmpord
cours€would meetfor a two-hourlaboratoryin additionto the thre€hoursof lecture. The
numberof credithoulsfor thecoursewouldbeincreased
from thr€eto four. In thelaboralory,
the studentswould be providedwith a workstationand the activitieswould be specihedin a
written lab descriptionand throughverbal instructionsfrom the instructor. The laboratory
activitieswould include,but not be limitedto, the following:
Implementingapplicationsin Ada usingprovidedADTS.
Conductingexperimentsthroughthe observationof timingsof variousalgonthmsto
hypothesize
or verify the run-timeefficiency.
Obs€rvhgthechangeia behaviorin algorithmslvheodifferentdatastructures
or different
implemeltationsare us€d.
Analyzingth€behaviorof algodthmsanddatastructures
throughtheuseof visualization
andanimationsoftware.
Illustrating and emphasirc mathematicalmncepts through the use of computer
simulations.
3. The useof algorithm visualizationrnd animationsoftwar".
We havealreadybegunexploringthe us€of algorithmvisualizationandanimationsoftwarein
laboratoriesat Hope Collegein the Introduction!o CompuierSciencccourseand in the
Algoritlrns course. T'histechniquehasbeenus€dwith greatsuccess
by othersaswen [2] [12].
We proposeintegratingtheuseofthis softwareto providelaboratoryexp€dences
andclassrcom
demonstrations
in the datastructurescouse.
Because
visualiz:tionrevealspattemsin thechangingdistributionof an arrayof valuesas they
are being sorted, it can aid studentsin doing in{epth analysisand comparisonof sorting
algorithms.Complicatedschemesfor implementingbalanc€dsearchtreescan be understood
more cl€ady throughgxaphicsdisplayand animationof the tse€structures.Algorithms for
searchingandperformingcomputations
on graphscanalsobe illustrat€dat the conceptualaIId
intuitive level throughvisualizationtechniques.For largedatastructures,graphicaldisplayof
statisticalinformation can le.ad!o a better unde$tandingof the asymptoticbehavior of
algorithms.
4, Inclusion of mathematicsin the data structur€scou$e.
Disdete mathematics
playsanimpofiantrole in a datastucturescourse.Theapproachwe are
implementingfor Foviding computersciencestudeotswith an adequate
backgroundin discrete
mathematics
is throushfte inclusionof themathematics
materialin thefint four coursesin the
computersciencesequenc€,This hasseveraladvantages
overtheofferingof a separate
course
on disqetemathematics:(1) Themathematics
thatis neededin thecomputersciencecurriculum
is coveredprior to or at fte sametime as the computersciencetopic that ne€dsit; @) The
studentslearnthe mathematics
in the contextof its applicationin computerscienc€,providing
additionalmotivationfor leamingit; (3) The computercan be utilized as a tool to assistin
leaning the mathematics
throughcomputersimulation.
PreviousRelate-d
Work
ProfessorDershemhasbeenactivein computersciencecurriculumdevelopment
for morethan
twentyyea$. His first activity wasin the designof a coursethat combinedthe teachingof
statisticsandcomputerscienc€[4]. His work on thatprojectwassupportedby a grantfrom the
NationalScigncefoundationandresultedin the publicationof a laboratorymanualfor usein
sucha course[5].
ProfessorDershemwasalsofundedby NSFfor thedevelopment
of a modularapproachto the
part
teachingof inttoduclorycomputerscienc€[6]. As a
of this project, two moduleson
prcblomsolvingwereproduced[4 [8].
More rec€ndy,Professo!De$hemhasco-authored
languages
a programming
text thatusesAda
pdmary
as the
languagefor thediscussion
of imperdtivelanguagec.ncepts[10]. This lext has
beenusedat Hope Collegefor tlrc pastfour yearsin both its pre-publicationand pubtished
forms.
ProfessorDe$hemhasalsobeenactivein cuniculumdevelopment
andin the activitiesof the
SpecialInterestGrcupon CompulerScienceEducation(SIGCSE)of the ACM. He servedas
programchair of the 1988SIGCSESymposium
andeditedtheproceedings
of that symposium
t91.
Facilities
Three computernetwork are in placeon the Hopecampuson which this project could be
implemented.The choiceof theplatformfor theseactivitieswill be madebasedon the status
of thesenetworlc at the time of implementation.The lhreenetwolks,which we will call the
Sun, VAX, and PC networks,are describedin the Appendixof this proposal. The college
alreadyhasthe Verdix VADS Ada environment
availableon the VAX network. If the Sunor
the PC networlGare usedfor implementation,
thenHop€Collegewill purchasea suitableAda
elvironmentfor useon thechosensystem,
labswill me€tin a classroomset
If the vAx or PC networksare chosenfor implementation,
up on campusthat conains28 Swan386SXmisocomputersthata.reon a local areanetwork.
Thesecomputersare arrangedin a clas$oomsettingsuitablefor crnductingthe lab described
capabilitieswith the vAx
in this proposal.Eachof thesesysiemsalso hascommunications
in this laboratory.
networkso that the useof eitherthe PCsor theVAX call be implemented
The PhysicsandMathematics
departments
at HopeCollegerec€ntlyrcceiveda grant from the
NsF ILI programfor theestabrishment
of a labontoryof 20 x-ieminals for the instructionof
elculus andphysics. Theexactnatureof this laboratoryhasnot yet beendetermined,but it is
possiblethatthis laboratory,with theterminalsconnected
to theCompuierSciencedepartment,s
Sunnetwork,couldbe.usedfor the laboratoryactivitiesof this project.
The decisionas to whichfacilitiesto usewill be madeafter the specifications
andavailability
of the X-leminal laboratoryhavebeendetermined.Algodthm visualizationand animation
development
softwareavailableon HopeCo egesystemsincludesGAIGSon pC systemsand
TANGOon theSuns.
Bibliography
[1] ACM CuniculumCommitteeon ComputerScienc€,Curriculum'78; Recommendations
for
the undergraduat€
in
computer
scie,rce,
CACM,22(3):
147-166,
March
1979.
Fogram
[2] Brown,M.H., AlgorithmAninutior, Cambridge,MA, MIT prcss, 1987.
[3] Denning,P.J.,Comer,D.8., cries, D., Mulder,M.C., Tucker,A.B., Tumer,A.J., and
Young,P.R.,Computing
asa disciplirc,CACM,32(1):9-23,
January,1989.
[4] Dershem,H.L., A courseon computingandstatisticsfor socialscience
of Dn
, pruceedings
hnferer0e on Qnpurers in the Undzryraduate
Currictla, At)allt^,GA, lgjL,
Exercises
[5] Dershem,H.L., Computer
Wentworth,NH, Compress,
for Elenv aty SraristicJ,
lnc., 1979.
[6] Dershem,H.L,, A modularinhoductory compuierscienc€caxw, SIGCSEBullain,
13(l):17-181,February,1981.
[fl Dershern,H.L., UMAP Module 477: CompurerProblen So/yir,g,Cambridge,MA,
BirliauserBoslon,Inc., 1981.
[8] Dershem,H.L., UMAPMdule 478: Iterationand ConputerProblenSoling, Cambridge,
MA, Birkhauser
Bosion,Inc., 1981.
[9] Dershem,H.L. (ed.), Proceedingsof thc NinateenthSIGCSETechnicalSymposiutn,
Associationfor ComputingMachinery,1988.
[10] De$hem, H.L. and Jipping, M.J., Programmingl,onguages:Modelsand Structures,
Belmont,CA, WadsworthPublishingCompany,1990.
[lU Feldman,M.8., Daa Abstattion with Ada, Reston,VA, R€stonPublishingCompany,
1985.
[12] Feldman,M.B., Teachingdatastructureswith Ada: an eight yearpe$p€ctive,,SfGelEBul-ktin 23{1)391a0; trffit,-7991.
[13] Gibbs,N.E. andTuck€r,A.B., Modelcurriculumfor a lib€ralans degrc€in computer
scierce,CACM,29(3):202-210,
March, 1986.
Naps,
T.L.
Algorithm
visualization
in computerscienc€laboratodes,SIGCSEBulletin,
n4l
22(1):105-1
10,February,1990.
Silver,
J-L.,
UsingAdato specifyandevaluaieprojectsin a datastructurcscours€,SIGCSE
[15]
Buuetin,23(l)1337340,
March,1991.
Tucker,
(eds.),
A.B. et al
ComputingCuricula 1991:Reponof thz ACM/IEEE-CSJoint
U6l
CurriculumTaskForce,New York, ACM Press,1991.
SectionC. Summaryof Deliy€rables
1. I-aboraloryManualfor Usein DataStructuresCourue.
A laboratorymanualsuitablefor use in conjunctionwith a data stuctures coursewill be
developedas a palt of this Foject. This manualwill containa descdptionof at least 20
laboratoryprojectswhichcanbe carriedout in a superviseilab setting,or allematively,caobe
givenas outside-of-class
will includedevelopingapplications
assignments,Thes€laboratories
usingprepaledAda packages,experimentalcomparison
of algodthmsand daa structuresto
observearldanalyzerun-timebehavior,computersimulations
to illustratemathematic€l
conc€pts,
ard algodthmvisualizations
andanirnations.Thislaboralorymanualwill bepublishedin a form
suitablefor distributionto othersinterestedin implementing
a datastructureslaboratoryand
provideduponrcquestfor thocastof production.
2. Ada packages
to supportthe DataSructuresI:boralories.
A numberof Ada packages
will be constuctedfor usein tlle laboratories.Thesewill include
packages
will all be mad€
for shcls, queues,s€quential
lists, trees,andgraphs.Thes€packages
availableto any interest€dpartiesfor usein datastucturesor otlEr relevantcourses.
3. Visualizationsand.Animations.
andanimationsdevelopedfor laboratoriesand
All datastructureand algorithmvisualizations
clas$oomdemonstrations
will be madeavailablefor us€by others.
4. Paperfor submissiotto SIGCSE
Bulletin.
materialswill be describ€din a
A descriptionof the datastructuescourseandthe associated
paper submitted!o the SICCTEBdkrtn and for presentationat the SIGCSE T€chnical
Symposium.
8
D. Summaryof Sch€duleand Mileslon€s
All work on thisprojectwil becardedoutby theProjectDfu€ctorwith Possibleassistance-&om
a stud€nt,contingenton theavailabilityof local fiaancialsupportfor the stMert assisgnt.
Date
Activi8
June199
Designdatastrucillescou$e aodliaboratories
July 1992
datastucturevisualizations'
ftite Ada packages,
to support
algodthm
visualiztions/animations
and
laboratories
Jan-Apr1993
Project Director will t€ach the newly designed
cou$e and concurrendy produce ttrc laboratory
manual
fvlay 193
ProjectDirectorwiU poduce the final boundhb
manualandffiiic paperaboutprojectfor SIGCSE
E. hopriefary Clains to R€sultc
The Project Dir-ectormakes!o proprietary claidN to any rcsultsor other artifacts supportingard
necessa,ry
for the use of this oourse.
10
F. Qualitications
of ProjectDirector
CIJRRICULUM VMAE
flerbert L. Dershem
Fiu,cation:
B.S.University
of Dayton,1965
M.S. (Computer
Science)
PurdueUniyersity,1967
Ph.D. (ComputerScience)PurdueUniversity,1969
Experience:
HopeCollege,AssistantProfessor,1969-74
Associat€
Prcfessor,
1974-81
Prcfessor,
1981-present
Chairof ComputerScienceDepa.rtment,
1976-present
OakRidgeNationalLaboratodes,Visiting ReserchScientist,1977-78
BostonUniyenity Overs€as
Program,Visiting professor,1982-83
HonorsgndAwarh:
NDEA Fellow,PurdueUniv€rsity,1965-68
HoneywellCorporationFellow, PurdueUnivenity, 1968-69
ProjectCOMPUTeAwarde€,DartmouthCollege,1972
NASA/ASEESummerFellow, coddardSpaceFtight Center,1926
OakRidgeAssociated
UniversitiesSummerFellow, 1977
Gtants:
CGdirector,'Infioductionof theComputeri.I theStatisticsCuniculum", NSF Offic€of
-73
Computing
Activities,1971
Director,"A ModularApproachto theIntoductory Coursein ComputerScience',NSF
LocalCourseImprovenentProgram,19?8-80
Co-Dir€ctor, "A Micrccomputerhboratory for use in TeachingStatistics', NSF
InstructionalScientificEquipmentProgram,1979-80
Director, 'CSNETMembershipin Supportof ComputerScienceRes€arch",NSF RUI
Program,1987-90
Publications:(23 totat,thosep€rtinentto this projectlistedin Bibliography)
Othermajorsowcesof support:None
Relatedprcp1salsWnding: Norle
ll
G" Budget
JuneJuly 1992
May 1993
ProjectDLector'sSalary
@/9acadernicyearsalary)
$11,800
B€nefitsfor ProjectDircctor
(30%of sarary)
$ 3,540
hoject DL€ctor'sSalary
(1/9 academicyearsalary)
$ 5,900
B€oefitsfor Proj€ctDirccto(
$ 1,70
B0%of ulary)
TotalR€quest
$23,010
A HopeCo egecon&ibution
will beproviding1/3release
timefor theproj€ctDbeclorduring
th€Spring1993senestswhileheis teaching
th€course8ndwiting th€laboratory
manual.
Theapproximate
amountof thatcontsibution
wouldbe l/6 of thehoject Director'Jacademic
yearsalarywhichwouldbe$8,800basedonhis 1991-92
salary.In addition,all hardware
and
softwarcn€€ded
project
b implement
provid€d
this
wil be
by HopeCo[ege.
t2
II. Appendix - Descriptiotr of Hope CouegeComput€r Networks
Computer ScienceDepartment Sun Network
Machine/Part
Peripherals
Sun4/360
Sun4/470
(2) Sun4/40s
(8) Sun4/60s
32 MB memory,688 MB disk,24o0baudmodem
32 MB memory,669 MB disk
12116
MB memory,207MB disk,3.5',floppy
16MB mernory,100MB disk, 3.5" floppy, GX graphics
coProcessor
16MB memory,100MB disk,3.5" floppy
20 MB memory,200 & 480 MB disk, 3.5" floppy
Parallelprocessing
unitshousedin Sun4/470
(3) Sun4/65s
Sun4/75
(32) INMOS Tr"anpute$
I-ab softwareincludesstandarddistributedsunos/unix software.This includesa distribution
of Sun's Openwindows,whichis a ve$ion of the X windowingsystem.In addition,several
packg€s have been purchas€dftom various vendorsincluding FrameMaker,SutrGKS,
SunPHIGS,Sunlink DM DECnetsutport software,Saber-C,DOS Windows,and Adobe
Ttanscript. INMOSlanguages
anddevelopm€flt
softwareareavailablefor theTranputers,T.he
lab usesseveralpublicdornainsoftwarepackages
includingTEX, EMACS, andDECnetutilities.
The lab's softwareard hardwareprovideaccessto the Intemetthrougha collegerwnedMerit
scP.
VAX Network
The coltegeowns t\r,o VAX 4000 syslemswhich servesthe entirc campuscommunityfor
academic,administrative,and library applications. This systemis accessiblefrom eieven
locationson campuswhichhavea total of 144stationsthat are Dubliclvavailabtefor student
access.In addition,thereare mfiy otherterminalsavailablein officesandlaboratoriesacross
the campus.
A wide selectionof softwareis availableon the VAX syslemsincludingthe Verdix VADS
syst€mfor Ada softwaredevelopment.
FC Network
There is a Novell loc€l area networkin the buildiog complexwhere this Foject will be
conductedthatconnects
49 386SXsystems
througha crmmonfile server.Twenty-eightof these
systemsarelocatedin a computerclassroom
thatincludes9 Epsonpli[ters, oneHp llserjet IIp
printer, anda projertionsystem,
13
4***,r"*
IE!qB0!!.uE
DAIE!
June 29' 1992
T0!
HerbDershem
FRol'lt
(evin Kraay
SUBJECT!
DeJenseAdv n-c6dResearchProject Auard
grani
C o n g r a t u l a t i o n so n y o u r a p p r o v a l f o r a D e f e n s eA d v ' n c e dR e s e r r c hP r o j e c t
c
o
u
r
s
e
i n i h e a o o u n t o f t 2 3 ' O 1 Of o r t h e p r o j e c t e n t i t l e d " U n d e r q r a d u a t e
D e v e l o p o e n itn s o f t { a r e s c i e n c e a n d A D A ' "
J h e a c c o u n t n u o b e r 5 - 2 2 6 5 5h a s b e e n a s s i g n e dt o t h i s g r a n t '
n u o b e rf o r a l l e x p e n 5 e sa i s o c i a t e d $ i t h t h e 9 r a n t '
Plerse uEe this
U l i l l y o u p l e 4 5 es e n d n e a c o p y o t t h e b u d g e tr n d S e c t i o n C o f t h e T e c h n i c a l
be rctiv'ted rhen thc budget
nropo:at for thi6 grant' The iccount nuaber lill
i5 receivod tnd €ntered into the Fin.ncial Record Syste'E'
inforartion
T h e D r u g - F r e el r o r k p l e c eA c t o f 1 t 8 8 r e q u i r e s H o p ec o l l e g e t o c e r t i f y t h a t $ e
r,jill naintein a drug-free oorkplace' This certification took place on the
e D D l i c a t i o n f o r t h e N S Fg r a n t u , h i c hy o u l , t e r ei w a r d e d .
I t a l s o r e q u i r e 5 t h e C o l t e g e t o p r o v i d e t o e a c h e t n p l o ) ' ' eoeo r k i n g i t h e
F e d e r a l l y s p o n s o r e dp r o g r a n t h e c o l l e q e ' s p o l i c y o n d r u g s ' A c o P y o f t h i s
poticy is ittached for your reference.
P l e a s e c o n t a c t i D ei f y o u h a v e a n y q u e s t i o n s .
A
n*u**ou
DEPARTMTNTOF COMPUTERSCIENCE
August 13, 1992
AagelaM. Coonce
Grants Oftcer
DefenseAdva.nced
Research
ProjectsAgency
ContractsManagementOfi ce
3701North Faidax Drive
ArJington,VA 22203-1714
Dear Ms. Coonce:
This letter is to makeformal the requestthat I madeto you in a telephoneco[ve$ationlast
mon!n.
to Hope Collegehaveits terI requestthat the DARPA grant numberMDA972-92-J-1030
June
18,
1993
to
June
18,
1994.
The
reasonfor this requestis
mina,tiondate changedfrom
that due to the late date that I wa.sinformedof the awardingof this grant, I lvasunable
to completethe activitiesof the grant originally scheduledfor the summerof 1992, This
requiresme to push the scheduleof the grant bark one entire year. My schedule,a revised
versionof that lound on page9 of rny proposal,ie as follows:
Activity
Date
Jan-Apr 1993 Project Directorwill tearh courseusingAda and generateideas
for laboratories.
Designda.tastructurescoumeand laboratories.
May 1993
June 1993
Write Ada packages,
data structurevisualizations,
to suppolt
and algorithmvisualizations/animations
Iaboratories.
Jan-Apr 1994 Prcject Directorwill ieachthe newly designed
courseand concurrentlyproducethe laboratory
manual.
Ma,y1994
Project Director will producethe final bouod lab
manualand write paper about project for SIGCSE,
If you haveany questionsabout this request,pleasecontactme sothat we candiscussthem.
Thank you lor a.11
of your help oo this matter. It has beeoa pleasureworkingwith you.
Sincerely,
$--qfiJo.jL
HerbertL. Dershem
H O L L A N D , M t C H t C A N , 1 9 412639 8 / 6 1 6 3 9 4 - 7 5 1 0
M E M O R A N D U M
Date: August19' 1992
To: Greg Olgers
fYom: Herb Dershem
Subject: Informatiotr for a trewsrcleasefor a grant receivedrecently
Greg,
informationabouta grant that I rcceioedrccentlg'Giae me a call if you need
H"ii it
"o*"
addi,ti,onal inlorm ati on,
Projects
HopeCollegehasreceiveda grant for $23,010from the DefenseAdvancedResearch
chairperson
Dershem,
L
egeucy (OARPA.).The project director will be Professorl{erbert
otile tfope CotteleComputerScienceDepartment.The title of thenprojectis "Useof Ada,
in the Teachingof Data Structures
Laboratories,aod Visua,lization
The purpooeof thia project will be to introducethe ugeof tbe Ada languageinto the Hope
Collegebaia Siructurescoursethrough ihe inclueionof a la'boratorywith the course'The
laboJory will makeentensiveuseof Ada,aod will includethe illustrationof data structure
conceptsibrough the use of visualizationand anima,tion. The Hope CollegeComputer
ScienceSun Workstationlaboratorywill providethe facilitiesfor the laboratolies'
professorDershemwill first ofer the Data structurescourseusingAda in the spring 1993
semester.During the eummerof 1993he will designthe laboratoriesto be includedin tbe
of 1994thoselaboratorieswill be conductedfor the first time'
course.In ihe Springsemester
ProfessorDershemwill summarizehis work in a scholarlypaperaod
In the summerof 19-94,
producea laboratorymanualtha,t cao be usedat other imtitutioos'
Ada was developedin the late 19?0sat the initiative of the U'S Departmetrtof Defense'
The purpose was to save money my standa,rdizingDefensesoftware developmentto one
language, DARPA funds the learning of Ada by students to encouragernore widespreaduse
ol th" l*guug.. ProfessorDershem' along with Professor Michael Jipping' has written a
programming languagestextbook that is basedon the Ada Ianguage
This is the fffth external graot receivedby Hope's Computer ScienceDepartment in the past
yea,r. Four ol these grants have been frorn federal agencies.In addition to this Srant from
DARPA, grants have also beenreceivedfrom the National ScienceFoundation and NASA'
A
Hooe Colleqe
Departmerit o;f Comprlter Science
lJrollc;nd, Miahig on 49 4 2 2 -I OOO
(676, 394-7570
A]
August22, 1995
Mr. EdwardBrown
DARPA Softwarc& lntelligent SystemsTechnologyOffice
3701North Fairfax Drive
l'llinglon, VA 222n3- l7 | 4
DearMr. Brown:
Enclosedyou will find two copiesof the final reportfor DARPA grantMDA972-92-J-1030.The
softwa& developedunderthis granthasb€enplacedin the ASSETlibrary at WestVirginia University,
I appreciatethe supportI receivedfor this project.I think that you will find the resultsto be useful.
Pleaselet me know if thereis anyother information0tat I canFovide for you.
Sincerely,
Heftert L. Dershem,Chair
Copy: Kevin KJaay
Enclosure:2 final teports
AdaVisionand THREADS:
Laboratories
andExperimental
AlgorithmAnimations
for Teachinga Data StructuresCoursein Ada
Dmrick P. Brown
Dept,of ComputerScience
HopeCollege
Ho[aod,MI49423
CheriJ. Bowsher
Science
Dept,of ComPuter
SaintJoseph'sCollege
IN 47978
Rensselaer,
HerbertL. Dershem
Dept.of ComputerScience
HopeCollege
Holland,MI 49423
Abstract
of a laboratory
Theoverallgoalof tbisplojectis !o continuetheimplementation
fs thedaa srucn[cs courseusingAdaandalgoritbmvisualizationandanination
thecou$eandconribulesto thelcartrThework dotrehoroenhancos
techniques.
The6rsthalf of theprojoc!entidedAdavision'is
of enrollcdstudents.
ing success
an instuctionalaid consistingof two BTt€€algorithmanimations.Thc s€cortd
a toolcalledTIIREADS,whichis usedto run experihalf of thepmjcctdescribes
B9trtsotrAdadatastructuesin a labotatorysetting.
INTORDUCTION
The overall goal of this project is to implement a labolatory for dre data sfuctures cou$e using
Ada, algorithm visualiation atrd animation techniques, and algorithm measuremontusing a tool
to guidctlFir wo* in
to be usedby studcnts
cauedTHREADS.Manualshavebeendeveloped
to theleaming
thecoursea]ldcontdbutes
thelaboratory.Theworkdonein thisptojectenhances
succe$sof the eNollod students.
Prcviouswolk on this projectiocludes6 completedalgodthm arfEcationsanda basisfor the
THREADS plogrxm. The proviouslyqeated aniruatj :rsinclude linked list, in6x to postfixcon's with rotations,splayttee zig-zlg and
version,binary treeinsertanddelete,AVL treeinsc
zig-zig rctations,andAVI- singleanddoublerotatious. hevious work on TI{READS included
tho qoatiorl of theinterfaceandfili]CamentalprogramroutirEs,
The philosophyusedin developil; :helaborxtorymaintainsthatindividual laboratorysessionsbe
closed,usgAda pacl.113s,involve algodthmmeasuementoxporimgnts,andmakeuseof algoridlm animation. A closodhboratory msansthat collectively,all studontshavei scheduledtime
to work in drc hb setti[g. 1^ninsfir.l.]r is alsopresontnt this time to aid anddircl their work.
anda,.. packages
thatdonot alreadyexistcan
developed,
Manyof d:eA:ir prckagosrlleahcr:.lJ'
Thus,
morc
datn
sltucturos
can
becoveredin thc coursg'
by
rtudr'rls.
impleurented
be easily
The animationshelp studc...sbecoruemorc familiar with algoritirxosandtho oxperinentsallow
studentsto oxpedencedifferontquiditiesof the algorithms. This Paperfocuseson tlte algodthm
animationsanda tool usedto run experimentson algorithmsin $e laboratory.
THREADS
LaboratorYExPeriments:
that
involverurmingtestsoo algodthms
thataroperfomredin tlle laboratolies
ManvexDeriments
catrbemeasupd
ffi;#ili-il;;il;riig
Esultsthat
prcduccd
tests
ea"pu"tug"t'These
involvedin their
Workingin thelabgivessirdentsthechanceo bemoredirectly
;;;J;;
theamouotof informationtbgyretain'
learning,incr€asing
butmolearoplovidedby
themselves'
will bewrittenby thestudents
Somoof dleAdapackagos
andalgorifiEs' stuarei*posedto moredat'-structures
thestodeots
-*liitp"tJ r"irtlt ru-ay,
ii"-i,"ri."aiof actuallv
theeffrctsof algoridmsin,stead
,ii"it timeseeingandexperiencing
a"rir
theirabilityto anasruitures' This shouldincrease
.oainn ,rt" if*-i rt-" ard conesponding-data
to a ptoblem'
and/orefdciencyof differctrtapProaches
lvze tf,eeffeclveness
arEplannedfor thofollowingappUcations:
Currently,experiments
1) Big OhExperiments
of difforcntsortingalgoridms
2) Compadson
3) Binarysoarchtee vs.AVL aoe
4) Hashcollisionhandling
5) Big Oh cocfflcicntevaluation
tool is tleeded'
in a laboraorysetting,anapFopri&te
In oldgrto run thcsgfyposor expenEents
of sucha tool' namedTHREADS'
consistsof thedevelopment
il;rn"d
;;;;;;ti!oiect
Bxpedment!onAdaDataStructu€s)is o toolthatcanbe
THRBADSCfestHamcssfor Repetitive
algolithms,reportingbackI' Jheusersometypeof tho
t ." ,iri, * AatasEuctuesand'bl-ack
and
sepamloly'
"*A
box' prcgramsthatatEimplcmentcd
;tt. Thetcstsarc
;;;;;;;;;,h"
aswell'
maybet€sFdandrun seParstely
HowtheStudentUsesTIIREADS
ThebasicicleabehindTHREADSis ilustraledby thefotlowingchart
BlackBox
DataSet
THREADS
a datasetbasedon infoErationgivenby theuser.Thisdatasotis usedby a
THREADSgenorates
it retumsto TIIREADSthe
blackboxto runoneexpedmed Upontheblackbox'scompletion,
will be
of tic tost. Themeasur€Elont
samolesizeof thedatasotandanintegermeasuremsnt
theuserruns'
includedin a tablethatkeepstrackof eachexpedment
inf-ormationneededfol tho
RunningTHREADSbdngsup theinterfaceshownin Figuo 12' All
are
theusernay designate
placesby theuser'Thepararoeters
datasetis inDutio theapprcpnatg
asfollows:
Method:Theblackboxto usefo! theexperiment
a
WJ," a fl", Thenamedfile wherethedatasetis storpd lf nofile is designated'
dofaultfile will beused'
temPorary
puti.tt
Thepatho thedirectorywbeleall datalnd files will bo wdtten'
Wri
genemted
bv
ijt" "nif"t ift" pu'rn*a nameof a dita setro beusedrnplaceof a file
THREADS.
of elemetsin thedataset'
Size:Thenumber
Samole
themndom
iiliri" o-lt*u"Jtt, Thestatisticalprobabittydistibutionusedto generated
dataset.
in thedataset'
SampieOrderl The€xtertof oderingimposedon eloments
randomlyfrom
datasetgenerated
rrr" a"i*Tt"ttingt at" for a 100element,iomll "tely unsorted
a unifom rardomdistsibution.
Method
s black
by theTHREADSprocess'WhenTHRBADSexecutes
i-h" blu"kbo* p.""rs is spawned
by TIIREADS' It thenwaitsfor theblackbox!o
toi, it gtu"t O. lf*t bo; a datasstgener&ted
Tableof Mea,"-iu* iVir* ,f," Uf*k boxreturns,iHREADS takssthedataandwlitssit to the
is
Theblackboxrentms2 integc$. Thc 6rstis thesizooftho dstasetandthesocond
;;;;;.
thatdleblackboxrgtums'
tlle tlgasurcment
on whichblack
Etumedby theblackboxwill varydo-pending
Thencaningof themeasuement
thatwere
maybethenumberofcomparisons
i"U"f"i-*". In somecasesthemolsurement
measure'cent
the
"
in a sortroutine.In thecsseof thobinarysearchEe€expedments,
oerfonned
will be
tho
mflsurement
howover,
cases,
In
all
l]:.e.
[ot"*ntt ,ttauu"Iag"dcpthof Enodcin the
dnra
struca.cjfiain
or effrciencyof
integit us;ful in analyzingthceffecdveness
a ion-negariue
ftom diffelentoxperiments
roturne'd
The
Eeasw€rnents
Jo" oi rrlo;trtrn foi a particulardati set.
againsteachotherto aidtheuser'ssnalysis'
canthenbecompared
Writeto File
thegenomted
Thetextfield labeled..wdteto File:'' takesa nameasinput. If a nameis speci.fied,
Pathi' text
in
the
"write
datasetwill be savedto a file wittr thatnarnein thcdiFctorysp€cified
filo'
thedatasetwill bs savedto a temporary
field. If no nameis specifred.
Write Path
The"WdtePath:"textfield takesa pathsuingasitrpul THREADSwill notoperateuntil a valid
pathis given. Thepathstringncedsto bea pathvheretheuserhasreadanilwriteperoissions'
tgfff,{ps .enls anawites oany datafiles' If it cannotI€adalldw te its data"it will notwork
to run a blackboxwithoutsupplingthewritc path,a noticeFompt
plopedy.If theusorattempts
information'
wili appearaadnoti$ theuserto supplyTHREADSwith theapplopriate
: S a r pel S iz e
: lLasuret|lent
Figure12
Use File
mustcontairrlheontitepathand
Tho"UseFilet' textfieldtakesa stnngasinput' Thistcxt stdng
will usothisdata
O" Jtt"nt" ," beused.If a validp;th andnameis givcn' TIIREADS
"i
a newdataseLTHREADSwill usea specifeddataset
"r-"
i.srcadof generating
;;;;;;a;;
a newdataset'the
datase-t'Thercfire, if thous* wishesto gene!"ate
;.;d ;;;;d;;w
strinein the"UseFile" textfield mustbedeleted'
SampleSize
to beincludedin thedata
frl"--u-pt" ,i"" n"ta auowsthousolto enterthenumbqof eloments
by-usingthom-ouseto click otrthe
*| t*gi"g no. f , 10000.Thesamplesi:o maybechanged
defaultis 100sloments'
oo]ao*? ,i,ro*r, ot ty manuallyenterirgthesizcinto thetoxtfield' The
SampleDistribution
Srffi;t"tb-i."
in whichthedataelemcntsar€to bedistribt"dt"atesthetypcof randomness
uted" Therearc six diffoFnt distributionsto chooseftom'
1) Uniforil.
2) Exponeotial.
3) Normal
4) Ca,|x|ma
5) l'Jisson
6) ljinom:
'urttolrlabeled'Distdbution Paramete$" If this
:eDistribution, thereis a
f" th" ilght tl," "i A r,..,Jowpanolwith numborfleldswi[ appea!(Figue 13)'
i"*n ir""Li"t
"
(Figule 13)
user
canmodify the distributionsby changirg the parux!With this distribution window Panel,the
etersfor eachdistribution
Thesedistributionscanbe usodto ovaluatehow the distributionof datacanaffoct diffelEntdata
structures.For nlost cases,Uniform distributionis sufficient. Futurgwork on distributions
includosthe dovelopmontof blackboxesthat fully utilize the SampleDistribution featue of
THREADS.
SamoleOrder
of odertheuserwouldlikei'. thodatasettobegenemted
ii"]u--ol" -d"r."f"rs !othedeglee
of thodatawill beir increasthat1007o
orderof 100means
*r!-* ["_ _]OO, f00. A sa-oiple
sortcd
A sampleorderof -100meansthat 10070ofthe datais in decreasing
value
Any
oi zeromeansthatthedatais in psrfcctlyradom^order'
"tO"r
"tio-e-t-"pf"
A valueof 50 meansthattlrctust 5070ofthe datais in
roo is acceptable.
i"i*Li-roo?a
is in nndom order'
sortedorder,ther€rnainder
increasing
il;il;;td*
Data Set
andodor
i-" drtu ."t i, g"n"ot"d basedon theinformationfrom tlrc samplesize,disaibution'
data
setcanalso
A
to fulfill theuscr'srequirements'
ut" rando6lygenerated
n"far. m"
"f",i""u
l-pon"A datasetusingthe"UseFilej' tcxt field by supplyinga pathandname'
"oto"-to- "
Tableof Measurements
The
by theusor,exporimelsmaybercpoated'
,.s m"y besavedin filesdosigoated
GI dutudutu
mayalsobesavcd,sotheusc!maycomeback
sessioir
o-Ui"ofIn"u*ut"rnltusftom anexperiment
rerord'
experiment
to rhedstaat a latertimeto continueinalysisor evenaddto thepre-vious
'File'
menu'
iaUt"r otetuueOty clickingthoright mousobuttonwhileon thotablo'Fromthe
:S"ue
table'
geviously
saved
load
in
a
as.,-.'anda savewindowwill appear'To
a-ft*r" tft" option
'File'
'Opcn'
monu.
ftom dre
choosetheoption
RunExperiment
to theapFoand-wdtton
Whenthc 'RunExperbre0abuttonis clicked,thedatr setis genera@d
andcxecuted'When0teblackboxfinishes'the
is spawned
Driarcfile, Next,theblackboxprosess
If dreuserhasnotproarewdttento thetlble of measuremcnts'
iamplesizeandmeasurement
infomcri , theuserwill benotiied to do soandno
uia"a THnSADS*irh thesppmpdate
exDerimentwillberun.Iftheblackboxabortsorcrxhes,theuse!willbenotifedthattherewas
an-erro!in thoblackboxandno datawill bewdtten!o thc tablo'
View Graph
Whentlre.ViewGraph'buttonisclicked,themeasurementscurrendyinthetablewillbeusedas
'xvgr' andmay be createdat anypoint ir
the coordinatesfor a graph. Graphsareg:rerated using
the expcrimentsession.Eachgriph is p'oducedin its own window with a uniquetitle' which
allows for easycoDtparisonbctweengraphs.
ClearTable
sesThe'CloarTablo'butlonallowstheusertocleartheableatanypointdulingaTI{READS
'Clear
Table'
sion. This enablesthe userto stat a rrewsotof expedmcntsat any time. Whcn thc
buttor is clickod a p(olopt will appearaskingif thcy really want to clear fte table' If "Clear
the tablowifl be cleated. If cancelis selecte4dreusef,will be Etumed to
Table' is selecte.d,
TIIREADS with no changes.
Coefficients
will appoar(Figue 14)'
If the 'Coefficients' buttoni$ clicked,a smallwindow with five buttons
'n' beingthe-samplesize' If one
The fivo buttonsar€log(n), n, olog(n),n2,andn to soDopower'
displayingttre coefficientsofthat particularBig
* *rt t*u
it
.i,rr"t" t"*"t
"pp"ar
"u"fJ,
tablo' For example,if the datain the tableis:
Oh of tho datain the
100
600
tf the n2 buttonis clickod the xlorB will appeardisplaying:
600 6.000000000E-02
100
requirec to be
This meansthat with n=100 andy=600,an expressionof the form y=cnz would
If this coef6ciontromainsrelitively constalt over manyvaluesof n' the function
;.OOOOOOOB-OZ.
process'
rspresentedis a goodcandidatefor the big-oh function of theblack box
Figute 14
Edp
'Help' buttonon th€TIIREADS-window,or by ptsssing
Helpmaybofoundbothby clickingthe
Thobuttoron theTIIREADSwindowwitl opena pop-upwhdow
theirelpLy on thekeyboard"
'help' keyol thekeyboardwill givea shortsumttratcontainscompletehelptext.Pushitrgthe
maryof helpfor thespoton thewindowwhelethecursoris pointing.
Ouit
If the'Quit' buttonis clicked,a noticepromptwill appearandaskif dleuserrcallywantsto quit'
thouserwill ber€tumedto themainTIIREADSFogramwithoutany
If cancoiis selscted,
'Quit'
THREADSwill oxit andcloseall witrdows'Alsowhen
is selectcd,
changes.If
filesremainin thespecitred
fileswill bedoloted8ono unwanted
ffnleOS ir qoit,oUtemporary
wdtepathdt€ctory.
THREADS T[torial
tr,"'"i'u'.utt*to;alprogamthatisincludedwifiTHREADS.Whenthisprogramuruna
alea"Thiswindowis sizod
tutotialtoxtin s smoll'able
compt"te
i,lilirii"p-"* ,rttintpt'ays-oe
fo{ easyrcfenonce
screen
*-,rtuiu-ii L prac.jnoxto tbetifi.EAos windowonthesarne
when working with TIIREADS.
For theInstructor
of 11fles anda Makefile' Thefilesandtheirconlentsareasfollows:
is composod
TIIRBADS
- --af,r"uOt,C,
Devcuido3'0'1'
Clgatedby thographicalilFrface codegeDeraor'
pefinitionsofliuets usedto roceiveinformstiol abouttheUII objocts'
,r,*"ar-ui.ru
Setsup theintedace,andbeginswaitingfor eventsto proccss'
tl[eads-ui.cc
Callbackfunctionsfor thc variouswidgetsontheinterface'Also
,t""ua.-t*Ut."",
containsanyauxiliaryfurctionsneededby TIIREADS'
Containsthehelptextrotievedby presing the"I{elp" keyon the
threads.info:
keYboard"
Containsthocompletohelptextdisplayedin theTHREADShelp
longhelp.info:
wirdow.
thegaphicaldatafor rheTHREADSicon.
Cont&ins
dEesds.icon:
Contahsthegnphicaldatafo! thoTIIREADSicor mask'
th€ads.mask
fo! xvgr.
Containstheprefcrences
xvgr.prcfs:
theicript thatis calledwhenonethecoe6cientbuttonsarc
Contains
coef,scpt:
clicked.
thcReturn
A verysmallplogramthatjust waitsuntil theuserpresses
a[et.cc:
koy; usedio coef'scpt.
be
Blnck boxesmay be addedto THREADSwith little efforl The spotswherethe codeneedsto
modiced arenarked by cosmcnts of the fo!m:
*/
/* NBW METHODS: addatrynew methodsherc
First, i! tho 6le dueads-ui.cc,iNert the line:
('Ir{cthod name");
(void) r,,rhdchoice.addChoic€
'Ir,iethod
name'is the nase to appearon the menuin the interfece'For eachncw method
where
addc4 a sioilaf line mustbe inserted.Thc lines needto bc addedto thecursnt listing of choices,
which is oarked in the codc.
Next, ir the file threadsjtubs.cc,addanodrcr"else if' condition of the form:
€lseif Gtrcmp(nethod,"\4e6odFile") == 0) {
stlcatGomDand,"MethodName');
In this section'MethodFile' is theexeautablefile , .,cfot theblack box.Eachnew methodne€ds
to haveits own casein the "if-else if' statomsnt.
New nothods can alsobo usedby placing themin ths blackboxdtectory ad typing the namoof
the nothod executablsin thi "Ivlethod:" tsxt field. This is mucheasierftom a FograrDmhg
aspect,but this requircstho userto type in lhe nameinsteadof being abloto selectit ftom the
menu.
Newtypesofdistributionsmayboaddedin a siroilarfashion.Themenuchoicesfor "SampleDistribution"arcaddedthosamowayasthoscfor "Method."A cles dednitionof whatrhedisaibuin the
tion meansandhowit will afrectrandomgencratiorof integorswill facilitatcthechangEs
codoof threads-ltubs.cc.
In thrcads_stubs.cc,
thesystemcallsusethefull pathnamesto executetheblackboxandto use
theo0le!includefiles. Checkthatthescpathsarecorpct,andchangetl:rm asappropliate.
CONCLUSION
As futur€ work on this Fojoct, further Adavision animatioltscould be geatedor animation$
which is exist aspart of the XIANGO packagecould bo Iefined for tho pu+ose of implementation into a datasfucturescourse. In €gard to THREADS, further useof the "SampleDistsibution" featureis yet to be found, andadditionalfeaturesmay be addedThe useof Adavision andTHREADSin a labomtorysettingis intendedto involve studentsmore
direcdy in their instructionthan a classrcomsettingalone. The animationsarcintendedto
improve students'unde$tandingof the datastructuresand algorithmsbeingtaught,andperfonning expedmentson the algorithos allow fte studentsto analyzeandexpedencethe effectiveness
andefficiencyof differentsolutionsto Foblems. It is hopedthat ftis projectdoesindeedenhanca
a datastruch{escourse,helpinginshuctors
conveyto students
theabstractconcepts
of thecourse
ard activelyinvolvethemin theinstruction.
BIBLIOGRAPHY
Donovan,Tommy. "Cetting Stanedwith TANCO." 1990.
Pross,William H., Brian P,Flannery SaulA. Teukolsky,William T. Vatorling. Nunerical Reciper. Cambddgel.l..iversityPrcss,Cambridge,
1986.
Stasko,JohnT. "BWE Prcgrnmmer'sManuat TANCO." Brcwn Univcrsity, 1990.
Stasko,JohnT. "TAN6O: A ftameworkandsystemfor algolithm anitL,*tion."ComputerYol.23,
No. 5, p. 27-38,1990.
Tume!, Paul J. "ACE/gr User'sManual:Gmphicsfor cxploratorydataanalysis." Centerfot
CoastalandLand-MarginResearch,OregonGladuatelnsdnr: of Sci. andTech.,1992.
Weiss,Malk A. Dard StrucnresandAlgorithtn Analysisin Ad.a.BenjaminCummingsPublishing
Co.Inc.,New York,1993.
AlgorithmAnimations:AdaVision
AdaVisionservesasa teachingtool for dau structuescoursostaughtin Ada by allowing students
to visualizedatastsuctureconcepts,ratherthanry to leatn atrdunderstandthe concoptsin an
abstractmanner,Using tlrc algorithmanimationpackageXIANGO, two-dimensional,color animatiollsareqEatedby combiningtwo files. The first file containstho implemootationof tho algolitllEr beingadmatedalongwith procedurecalls to the secold fi10,which consistsof dle
animationscenes.The structu€s anddatainvolvod in the algodthmimplgmentatiotrareEpresentedin the aoimationscenesby imageswhich move asa rcsult of intErestingevents,suchasthe
insertionof a rcde into a linked list.
Someof the previousanimationsqoetedfot the AdaVisionprojectdisplaythe conespondingAda
codeon the XIANGO window asthe algorithmis beioganimated This displayof codeenables
studentsto view the connectionbetweenAda codeandthe actionof algodftms on dataanddata
structurcs.At tho beginningof an animation,tho fi$t line of Ada codeis higl ighted by a rcctangular image. Succeedinglines of codearc thenhighlightedasdreyare executedwithin the algorithm implementation,allowing studentsto obsorvethe moveme of imagesuting placein
conjunctionwith the higtiighted code.
The two mostcurent AdaVisionanimationsillustratoinseltionsanddeletionson a BTree. Due to
ttre complexityof the BTloo algorithm,theseanimationsdo not include the conespondingAda
codoaspafi of their displays. Also dueto comploxity,andbecausethe implomentationis rct necessaryfor what the animationsate intendodto illustrate,the actualBTtee algorithmis not implomentodinto the file which normally would containthe &lgodthmimplomentation.Instead,each
the possiblcsctionsthat would be perforued on a particular
animationmorelydemonstrates
BTfee if an insertionor deletionwerc to occur.
Within eachof tho BTreeanimations,as a valueis insenedor deleted,imageswhich replesont
nodes,Iinks andvaluesarerepositionedaccordingly. NodescontainingYaluesthat 8ronot releby empty,smaller-sized,rectangular
vant to the particularBThcgdomonstration8rorEpresented
imagcs,while nodescontainingvaluoswhich als necossaryfor ths demonsEationarcrepresented
by non-empty,larger-sized,rectangularimages. The conditionof the particularBTreethat is
showndependson the user'stesponsoto a sedesof questionsregardingtho BTreehe o! she
would like to view. Thosequestionsareaskodin the folm of a dialoguebeforean animationis
shown. Oncstho adlnatiort is displayed,a label describingthe insertionor deletionbeingperformedis writlen nea!the bottomof the XTANGO window. Also, in the upperleft cornerof the
window is a displayof text which indicatesthe value beinginsenodor deleled. The BTreedelotion aniration additionallyincludesa shorttext phlase which explainswhat is occurringwithin
the BTleo at tho momentthat the imagesaremoving.
BTtee Insertion
The BTreeinsertionarimatioo illustratesfour possiblgway$for a valueto be insertedinto a
whoseancestoris non-fuII, or into thg
BTree:into a non-full leaf, a leaf whosepalentis non-fu11,
leaf of a BTreowhich doesnot fit a.nyof thesecases,in which casethe root is split. The anima-
regardingthetypeof BTreointo whichhe
a dialoguowhichaskstheuserquestions
tion conlaiDs
to thoquesperfumed
on thous€r'srcsponso
Dopending
or shewouldlike to seeanimertion
hsortionsimulationis shown.
tions,thc appropriate
Thecasein whichthevalue"100" is insertedioio e leafwhoscparqltis trotr-rulis illustrated
below.
Figur 1. Theoriginalfofm of theBTbo is displayed'
Figure2. Thevalue"100" movesdowntbroughthctopof thea€e.
Figu:e3. Thevalue"100" movesdowntlroughthcparcntnodc.
Figu€ 4. The valuc "100" movesinto its cctect pleceh the leaf,
Ftguro5. fbe micldlo
valueof thelcof,"90', movcsupro
thoparontnodcandtholoafle split.
Figur€6. The split nodes,aloogrviththeirvaluesard linr.s, arcDDositioncd
BTreeDeletion
TheBTre€delotionanimationillustatessix possiblewaysfor I valuoto b€deletedfrom a BTtee:
from a rton-leaf,a leafthatis largerthanminimumsize,a leafwhosoneighboris largerthanminimud size,whoseparentis largerthanminimumsize,whoseancestor
is largettharrminimum
size,or a ddetionfiom a BTrccwhichdoesnotfit anyof thesecases,
in whichcasetherootis dissolved.Similarto theBTrc€insortion,lhis animationcontainsa dialogueof questions.Deperding on theuser'srespons€
to thequestions
asked,theappropdate
deletionsimulationis shown.
Thedeletionof a valuefrom thctrceis illu$tatodasthevaluomovosdownandinto a ,,garbage
can"image.
Thocassin whichthevalue"100"is deleicdftom aleafwhoseparcntis largerthantheminimum
$izoi$ illustratedbelow.
DELEltOu FR04 LEnF, lEHr I'ttrlrtr',,
aoTH HElct€ots MtNllul, P4REM,iot H$udLtl
Figure 7. The ciginal form of the BTrce is displayod-
DELError{noi !tnF, LEiF tlltti.al,
30tH rlal6l€0nE m*$ul, pnftm *Er $tfltiu,t
Figurc8. Thcvalue"100" is movodinto dredolotion..garbage
can.',
N.Fa. dlh
. h.tahbor.
Dril$r0fi a$r,, Llir, r*Jr rit|{lriun
roTH xErcr6as rirxr[r{
mtElrT Hor |ttnltit.t
Figruc 9, The value"50" is Eovcd dou,nso that the loaf may rogainits orlct
lrtltltoN lrtll lllAl, t|:tr r,tlrttnx.
afiH ilEtd$rBot8HlliDt-it, pr|IEl{t ilot tl|ltl,iw
Figur€10.Theleafonditsneighbor
mergo.
EOTHXErotBmgrltt$tti.
pilE|{r Ngl tlHrxrtt
Figu! 11. Th€two nodas,tbeirlinks,andvalucsasrepositioned
asone.
DataStructureswith Ada Packages,
Laboratories,andAnimations
Herbert L. Derch€m
Wendy L. Barth
Cheri J. Bowsher
Darrick P. Brown
1.0 Introduction
The datastructurescourseis oneof the oldestandmoststablecoursesin the comPutersciencecurriculum.It hasb€enpresentin all modelcuricula andcuniculum rccommendations ftom 1967on, andits contenthasrernainedremarkablystable'
havebeenintloOver thg history of the datastructurescourse,manytools andapproaches
using a
was
designed
a
courso
that
ducedandeffectively employed.This paperdescribes
combinationof threesuchtools: the Ada programminglanguage,algorithmvisualization
andanimation,and labontories with expcrimentalalgorithmanalysis.The tools developedandusedare describedin detail.
2.0 The Ada ProgrammingLanguage
The useof Ada in the dataEtructuescoursewaspioneeredby Feldman[3] andmore
recentlyadvocatedby Silver [6]. Severalvery gooddatastructurestoxtbooksarebasedon
the Ada languageincludingFeldman[2]' Weiss[9], Hillam [4], andStubbsandWebre[8]'
The advantagesof Ada in a datastructuEscourseincludethe following:
. Packagesaodprivate typesallow the completeimplementationof abstractdatatyPes
including encapsulationandthe separationof specificationfrom implsmentation'
. Genericsenablostudentsto work at a higherlevel of abstractionwhenconstructing
absfiactdatatYPs.
. Exceptionhandtingcanbe includedwithin abstractdatatypesto fufiher enhance
encapsulation.
In the coulsedescribedhere,studentswereprcvidedwith a libnry of Ada packageswhich
they usedin tleir programmingprojectsand laboratoryexercisesThis enabledthe studentsto usethe datastructuresin their own programswithout needingto implementthem
in detail.The codefrom the packageswasavailablefor studentsto examineand wasused
in the classto aid in the understandingof datastructureandalgoridm implementation'
Packagesthat areprovidedin the library are:
Dala Studus
wnh Ad! P&kasps,Llboototi*.
md Aninu!@
AVI- Trees
Rationalnumbers
Unlimited precisionintegers
Binary sealchtrees
Binary heaps
Itftist heaps
Linkedlists
Queues
Stacks
. B-trees
. SPIaYtrees
from thosefoundin Weiss[9]'
wereadapted
Someofthesepackages
3.0 Atgorithm Visualizations and Animations
in datashuctules
andanimationhasbeenusedsuccessfully
Algorithmvisualization
arefoundin Brown[l] andNaps[5] Toolshavebeen
coirsesfor sometime.Examples
describedwhich facilitate thtdevelopmentof theseanimationsThe tool chosenfor usein
thepresentprojectis XTango[7].
areusedfor bothclassandanimations
course,visualizations
In thepresentdatastructures
to enhancestuintended
room demonstrationandusein the laboratory.The animationsare
dentunderstandingof algorithms,particularlysincetheythe studentsdo not write codeto
illustratethealgorithmthrough
Mostanimations
implementthe algorithmsin mostcases.
thealgowith theAdacodewhichimpl€ments
an animationthaiis viewedsimultaneously
is
animated'
rithm. Ada statementsin the codedisplayarehighlightedastheir action
Many animationsareprovidedwith thedistributionof XTango Someof thesewerefound
to be appropriatefor usein the datastructurescourse,often with minor modifications ln
addition,oti-reranimationsweredevelopedasa part of the coursedevelopmentptoject'
were:
Thosedeveloped
. Linked lists with insertion,deletion,andsearch
. Infix to postf,x expressionconverslon
. Binary searchtree insertionanddeletion
. AVL tree rotaflon
. AVL tree insertion
. SPIaYtlee rotatron
. B-tlee iNertion
Dab Srrudues sith Ada Packages,Ilt)oaton6.
ed Anidiio's
found in
A more detaileddescriptionof theseanimationsalongwith illustrationsare
AppendixA.
4.0 The Laboratories
the stuThereare eight labontory exerciseswritten for this course'Someof theserequire
funnens qf"st Harnessfor the Repeat€dExecutionof Ada
J"ns to ur"-u p*tug"
"it"o
on Data Structures).THREADS is descdbedin AppendixB'
brief
Descriptionsof the laboratoryexercisesarefound in Appendix C' The titles and
descriptionsare given below.
I . Writing an Ada Program
the
fh" ,tia"ntt -" intitoducedto the Ada larguageby writing a programto compute
nth power of 2 usingintegersandfloats.They arealso requiredto writc a.Program
whiih usesNewtoJs me*rodto calculatethe squarcroot of 2' Studentsobservethe
limitationsof sizeandaccuracywith Ada'sbuilt-innumerictyPes'
2. Using Ada Packages
2 They
StudJntsusea paJkagecalledBig-Inleger to obtainresultsfor lar-ger powersof
alsousea rational numberpackagoto oblain moreaccuraterosultsfor the squarcroot
of 2.
3. Using GenericPackages
StudJntsusea genericrationalpackageandinstantiateit for Big-Integer to ilcreasethe
accuracyof the squareroot of 2 calculation
4. Big Oh Sampling
Fiie algorithmsareprovidedin Ada programswith variousBig Oh values-students
run th; throughTHREADSto obsewetheir timing behaviorboth in tabularand
graphicalform.
5. Big Oh Determination
Sddentswork with l0 algodthmswhosebig Oh behaviorsth€y must analyzeand
obsorve.
6. StacksandQueues
Studentsrun animationsin XTangoto observeand analyzethe behaviorof a stack
dnfix to Postfixconversion)anda queue(PostOffic€ QueueSimulation)'
7. ComDarisonof AVL andBinary searchTEes
Studints usepackagesfor AVL tre€sandBinary Searchtreesto obseweandcompare
timesandavenge depthof an elementin
their behavioisin termsof search/insertion
the tre€.THREADS is used!o performthe analysison tie observatrons'
8. SortComparisons
THREADS is usedto comparethe behaviorof five different sort algorithmsover variousdatadistributions.
Data Strudc
*ith Ad! P&k!g€s, hloratoics'
ed Anim'lions
5.0 Project Activities
The project wasconductedon the following time table:
1. June-July1993
written, datastructurevisualizations
Courseandlaboratoriesdesigned,Ada Packages
constructedto supportlaboratodes.ProfessorDershemwasassistedby WendyBarth
andCheri Bowsherwith supportfrom a NationalScienceFoundationResearchExperiencesfor Uldergraduatesprogam g.ant.Also' studentBob Chenassisted
2. November1993
Resultsof work of previoussummerwerepresentedby WendyBarth andChe'i Bowsherat the Argonn; NationalLaboratoriesSymposiumon UndergraduateResearch'
3. March 1994
Seminaron algorithmanimationwaspresentedat theUnitedStatesAir ForceAcademy
dudngtheprevioussummer
developed
animations
discussing
4. June-July1994
Coursematerialsfinalized,Documentationpreparedfor softwareproducts Professor
by CheriBowsherandDaffickBrownwith suPportftom a
Dershemwasassisted
programgrant'
for Undergraduates
National ScienceFoundationResearchExPeriences
1994
5. Fall Semester
ProfessorDershemwasprovided l/3 releas€time by HopeCollegefor the prePantion
of the coursematerialsin the teachingof the cou$e'
6. November1993
by Dadck BrownandCheriBowResultsof work ofprcvioussummerwerepresented
Research'
sherat the ArgonneNationalLaboratoriesSymposiumon Undergraduate
1995
7. SpringSemester
at HopeColPiofeisorDershemusedthefinalmaterialsin CSCI286,DataStructures,
lego.
8. August1995
Final report wasprepared.
DaraSbdu6
wi6 Ada P@kases,Laboolorid. andAninalions
BIBLIOGRAPHY
[1] Brown, M.H., Algorithm Anim,tian, Clrlrbidge, MA,
MIT Press'1987
Company'
[2] Feldman,M.8., Data Abstracrtonwith Ada, Reston,VA, RestonPublishing
19851
eight yearPe$pective,S/GCSE
[3] Feldman,M.B., Teachingdatastructureswith Ada: an
June,1990.
Bu etin,22.Q)t2l-29,
l4lldlillajm,B., Introductionto AbstroctData TypesIJshg
Prentice-Hall,1994
Ada,Englewood Cliffs' NJ'
laboratodes, SIGCSEBulletin'
[5] Naps,T.L. Algorithrn visualizationir computerscience
1990.
22(l): 105-l10,Fobruary,
projectsin a datastructutescourse'
[6] Silver, J.L., Uiing Ada to specifyard evaluate
Butletin,23(l):337-340'March'1991'
SIGCSE
anilrrztion,Computer'
Fl Stasko,JohnT. TANGO:A frameworkandsystemfor algorithm
23(5't:2'l -38, 1990.
Data Typesmd Ada'Bos'
[8] Stubbs,D.F.andN .W.Webrc,Data Structuresvith Abstract
ton.PWSKent, 1993.
Ada, New York' Benjamin
[9] Weiss,Mark A. Data StructurcsandAlSorithn Analysisln
CunmingsPublishingCo.Inc.' 1993.
Daia Stucturcs wiih Ada Pattg6, Labodtori.s &d Alination
paec5
AppendixB
& Animation
AdaVision- Visualization
AdaVisioncombinesAdacodewithdynamicimagestoserveasateachinstoolfordatastructure
coursestaughtin Ada. Using the algorithmanimationpackageXTANGO, animationsarecreated
on dataand
so ,tudens-muyniet the connectionbetweenAda codeandthe actionof algorithms
with each
datastructures.With the exceptionof the AVL insertiol, the Ada codeassociated
arenot
algorithm apPearsin the displayareaof XTANGO In somecases,procedureswhich
explicitlydisplayedareusedin orderto simplifythecode'
by images'Theseimagesmove
The structuresand datainvolvedin an algorithmare represented
of a
events,suchastheinse(ionofa nodeintoa fteeor themovement
astheresultof interesting
thefirst line of Ada codeis highlightedby
ilntin a rotatlon.e.t theieginningof eachanimation,
linesof codearehighlightedastheyarcexecutedTheuser
image.Succeeding
a rectangular
takingplacein conjunctionwith thecodehighlighting'
imagemovement
observei'the
Linked List
andfindsarcdoneon a linkedlist with a
how inserts,deletes,
The list animationdemonsfiates
dummyheadernode.Insenmaybedoneatanypointwithinthelist,deletewillremovealloccur.
in
rencesof a particularvalueftom the list, andfind will searchfor the frrst occurrenceof a value
thelist.
XTANGo,sanimationwindowappears'andafterthe.runanimation,buttonisclicked,allinterthere,givingtheuserthe
actionwith thouserwill occurin ihe shellwindow.A menuis displayed
quitting
the
application'
optionsof insertinga node,deletinga node,findinga node,or
If the userchoosesto inserta node,sarewill be promptedfor the valueto be inserted,andthen
promptedforthedesi'edplacetoinsertthenode:githeratthestaltofthelist,thoendofthelist'or
after anotheruser-specifiednode lf theuserdesiresto deletea node,s/hewill bepromptcdfor the
valueto be deleted,andinformedthat all [odes containingthe valuawill be deleted.If the user
choosesto find a value in the list, s/hewill be promptedfor the valueto find, andinfomed that
only the first occurrenceof the valuewill befound.After all informationfor a particularoperation
hasbeengatheredfrom the user,the animationbegins'
In an insert,an externalpointerfinds the nodeto be insertedafter anda new nodeis drawn and
addedto the list. In a deiete,an extemalpointerfinds both the nod€to be deleiedandthe node
immediaiglybeforeit prior to deletingthe node.In a find, a comparisonis animatedbetweeneach
elementof the list andthe find value.The frnd valueappearsin the lower Ieft coner of the display
area,andaseachelomentisvisited,thefindvaluemovesnexttothevalueofthenode.Ifthevaluesmarch,the imagesflash.If theydo not match,the find valuereturnsto its placein the comer'
the valueof
Nodesare representedby divided rectanglesThe teft half of the rettanglecontains
poirters'
suchasthose
the node,while the righthalf holdsa pointerto the nextnode Any extemal
App.ndix B Ad tsion \tsldizaion
& Anination
of the list image' The
usedto f,nd a certainnodein the list' appearandmovealongthe bottom
window' and after an
-o"rponang to eachoperationappearsat the top of the animation
"oO"
it is erased'mJ original list consissof a poinler namedFIEAD that
ft'-*"f"""a'
points to NULL As lists
"*raii-o"
oli"" a a"*-v tt"ader,that is, atremptynodewhosepointer6eld
"
viewedby
i""o." fong,ttt.y *ill moveoff the displayarcato the right' The imagescan still be
window'
usins
' the ar;ow buttonson the left sideof the XTANGO
Prev-CeII != Find(inPut-vaLue' L);
T e m p : = n e r , lN o d e ' ( X . P r e v - C e 1 l . N e x t ) i
HEAD
eII.Next := Tempi
NULL
e
Prev-CeIL
TernP
Figure l. Inscdng a nodeat the stalt of a linked list
Infix to Postfix ConYersion
'postfix' animalesan infix to postfix conversion'After clicking-XTANco's 'Run
Adavision's
Animation'button,the useris askedto enteraninfix expression'This original streamof characters
,INPI-IT,in the XTANGO window.The posdix expressionis built and
below the label
aDDears
'OUTPUT' andthe opolatorsarestorcdin a 'STACK' imageasthey are
oiacedunderthe labet
proccsed.
Throughoutthe animation'ana'tow is usedto point to the characterof ths inPutstream
'nhich
linesof Adacode-arealsodisplayedand
is *rrently-und"r consideration.Thecorresponding
is performed.Executionis completedwhenall symbolsin the infix
,tt"
ttigttUlft
"t been
"a have
"onversion
alld the stackis emPty'
expression
Processed
Itisassumgdinthisaninationthattheuserhasapreviousunderstandingofstackoperations'such
aspopandpush.Oncea chamcter,or symbol'is read,it is pushedontoeither STACK or OUTPUT'
ln op"r-a U tnt innx expressionmovesdire4tlyfrom the input to the output saeam'If an
ooeritor is encountered,it is movedto tlrc outputafter all opentorswith a lesserprecedenceare
poppedfrom the stackandpushedonto the output.A compadsonbetweenrheol)eratorbeing
consideredin the input andthe operalorat the top of the stacki6 indicatedby a blinking top-ofstackelement.
Affidix
B Adavsion - Visualizrion & Atirndion
havethe highgstpriority' while dght.pajentheseshave
ln comparingoperators,left Parentheses
is
will neverbe pushgdontothe-stack lf a dght parcntheses
none.fns ,ieuns rigfrt pareotheses
will be poppedfrom tle stackandput in dre outputuntil a left oneis
;;;;;;;;;*
andsoro parenthesiseverappearin
i"*f,"J. rft" r"ft p"r".,t .ses iittr.en removerlfrom the stack,
the outDut.
coNvEFSpX
shilo
60€
aFolli
ll'lFrx To Fo5TFtr(
.n4-of-inpuc-IooP
( ( 3 ' o ) + 6 / r )
( next-ssmbol
)
opoF.hd
) :
puc ( noxt-39mboI
= -)nox€-.smbol
olsl,F
(?
toP(6!ack)/=uhr.I6
);
Put<|ooP(st'ck)
4
th'n
1F
STACK
then
.looP
|6oP (3€ack):
ond th'n
noe EmPts(3t.ek)
dhtl6
) <=Prlorrbs
<nsxt-cs.nboI
P.l6rlcg
Lh'n
,/-'<'>
1€ (top (ctack)
(
P
o
P
(
c
t
l
c
k
)
)
:
Pqt
6nd
I6oP,
puch <noxc-ssiboI
(lop(cc.ok)
)
IooP
) i
ot 'lPuT
Ioo|c
noE EnPtg<3tock)
uh1t.
pue <Pop <ttack> ) t
Figure2. Theinfix streamis placedin IMUT.
col{vEFsF
tt<ttrr
l.tqlo
FoE
fx
II{FUT
noc ond-oa-lhpqt-lo6P
ohr.l.
).t
3.! (n.xl-a!FboI
L€ oF. r.hd ( h.xt-.smbo]
):
Futs(n.xt-.!6bof
ELi?
) . . /
)
t )
f
!h'h
..rE-=6EEr=__._r'--EF;A
dhrI.
put
coP(st.ck)?z='
(P6F <o!.ok)
) t
('
IooF
poF <.c.ck),
dnd th'h
noe Empcs(.l.ck)
dhlLo
(noxt-3sFbol,
> <=Pri orlts
Pr!oF1tg
Ehon
(toP (.E.ck)
t/='<'t
rF
),
Pu€<PoP(cc.ck)
pqsh
( n.:€-alrbo.r
n6€ EmPts(sc.ck)
uhrlc
),
pu€ (PoP (ct.ck)
(toP
(3t!ck)
)
Ioop
(
):
loop
Figure 3, The symbolsarc processed,movedonto STACK andinto oUTPUT.
Appodir B Adavsion
vsualizarion & Animdion
+
Figure 4: The final postfixexpressionappearsin OUTPUT'
Binary ScarchTree
inscrtionsanddgletionson a binary searchtree'
Adavision's "bintree" animationdemonstrates
the right sideof the displayarea,andthe Ada codeis shownon the left
il" o* it aUf"V"a
"n
sidc.
seecompalisons'If
Upon besinninqthe animation,ttle usoris askedwhetheror not s/ltc wantsto
viewing of the anima,fr! uter int*"i Xnttativcly' all comparisonswill be animatcdduringthe
if the inseras
follows:
tre€
,i"" ir," *" u"itt""a iinmediatelybjfore a valuemovesdownthe
less-thansign
iion uAo" it f"tt ttt- the existingnode,it movesto the left of the nodeanda
it movesto the
node,
aop"ursu"t*e"n ttte ualues.If the new valueis gleaterthanthe existing
After making this
,i?f,i. f,f," ur". ao"r not wish to seethe comparisons,s/heshouldanswerno.
in the shell window.The userinputswhich operations/hewould like to
JiiSoq u -*u
"pp"ars
see,alongwith the valueto be insertedinto or deletedfrom the troe'
level of recursionis shownby
The Ada codefor both insettionsanddeletionsis rcursive' Each
'dim' by changingcolor wherla new
outlining the treecurrentlyunderconsideration.Old outlines
call'
level of-rpcursionis entered.All codeis erasedandrewrittento showeachrecursive
then movesto
Whonan insertionis animated'the new valueapPearsin the upp€rleft comer aIId
position:
left
if less' tight if
the root position,The new valueslidesdowntothe appropriatechild
qreatertiranthe node.This continuesuntil the oew valuefinds an emptyposition or encountersa
If the new valuefindsartemptyposition,a new link is drawnto comect it
i.J .f m" t^-"
"a*.-ay appearmorethanoncein thetree,soif theuserdoestry to insert a value
uuto"
to tt
in O" tree,the nodewitl flash,andthercw copy of the valuewill be movedout
tft"t "?".-f'lo
Ai"uny
"*ittt
of the fiee.
the deletion
A deletionis animatedin similar fashion,excoptthat we aresearchingto match
the nodebeing deletedis
value.once the valuehasbeenfound, the correctIeplacementflashes,
'pulled'
'lifted' out of the tree,andthe replac€mentnodeor suB-Treeis
into placeby the link that
App.
'x B Ad.Vsion - visurlizdion & Anitulion
the deletionvalue' the
DreviouslyDointedto the deletednode.If no nodeis foundthat matches
'lifted'
out of dretree'
Ltetion vaiuewill be
ft-Iffisl
T := nd Tree_Node- (x.
.tslfX<T.EIdentth.n
T.L.€t) i
In.crt()(cls1fX>T.E.Lm.htth.n
T. Rtghl) i
fns.rt(X.
nurr.
Figure5. Insertinga nodeinto a suB-Tree
AVL TheeRotation
'avlrotat' demonstrates
singleanddoublerotationsof an AVL tre€uponthe insertion
Adavision's
times asdesiredby choosingan
of an element,The usermay view anyof four rotationsasmany
'Run Anination' button'
option numberin a shell window after clicking XTANGO'S
andB'
In the singleleft rotation,lhereexistnodesA andB' whereA is the original root of the trce
triangles
i, ti," ,oot which resultsfrom the rotation,The tre€ is filled in by threr
e, t"tt
'n'
A'
"i'ita,
*tri"tt t"pi"r"nt tuS-Tre€sof depth . The doubleleft rotationconsistsof thrconodeimages:
this
case'
the orig;al root; B, A s left child; andC, which is B's right child andthe new root ln
of depth
the tre; is frlled by two triangularsuB-Treesof depthn, andtwo triangula! suB-Tre-€s
in+l'. The nodesln eachrotationarEconncctedto suB-Tre€sby way of'links,' which serveas
pointen to nodesin the tuee.Thc singleright anddoublodght rotationsare mirror imagesof the
left rotations.
The elementis lepresentedby a small,olaugetdanglewhich fust appearsin the top dght-hand
comer of the XTiNGO window.After working its way down the tlee in standardbinary search
potentiallycaustre€fashion,the elementatt2rhes,or inserts,itself to the bottomof a suB-Tree,
of the
suB-Tree
ing the tre€ to becomeunbalaoced.The elemontis insertedinto the left-most
oiiot for rhe sinsle left rotation,the right-mostsuB-Trcefor the singleright rctation, the right
of thepivot for thedoubleleft rotation,andthe left suB-Treeof the right
of,n"i"r,
IJ-t
"r,itd
child of""the pivot for tie doubledght rotation'
approEachrotationalsohasirs own displayof Adacode.As eachline of codeis highlighted,the
irnage
The
rotation
occurs
Driatelink movementis perfomed. Orco all links arein position,the
li eachnodemovesto its new positionin the balanc€dtree andthe links are redrawnaccordingly,
A@dir
B Adavision - Msualizltio & Aninatiot
DoubI--Riahe
Ro€.e1on
Figure 6 . The repositioningof link dueto the insertionof an elementinto a suB-Tree'
t oot
:=
c:l
AVL treefollowingtheperfomanceof a doublerightrotation'
Fieure7. A balanced
AVL Ttee Insertion
into an AVL tree This animation
insertions
AdaVision's"avlins"animationdemonstrates
assumesthat the useraheadyhasa working knowledgeof the four typesof AVL rotations:single
in theanimationwindow'but
left, singleright,doubleleft, anddoubleright.No codeis displayed
the useris notified which rotationis beingperformed'
'run animation'buttonon the XTANGO window,the useris promptedfor the
Aftor pressingthe
into the tree.valuesmay be betwern 1 and 1000,with 0 servingasthe quit
valueto be in-serted
option. The userinputsthe values/hewould like to seeinserted,andthe animationproceedsfrom
there.
the
First, the insertioninto the tree is animated,The new valueappearsin the upperleft comerof
displaywindow,while the root of thg treeis surroundedby a blue circle' This blue lozengemarks
the
the position in the treecurrentlybeingcomParedwith the new value,ard witl eventuallymark
comspoiwhere the value is to be piaced.Next, the circled nodeflashesto showthat it is being
the
lozoaredto the insertionvalue.If the new valueis lossthall or equalto the surrouldednode,
the node'
!ng" mou"s to tlt" positioo of the left child of the node lf the new value is Sreaterthan
the-lozengemovesio the right child's position.After the conect moveof the lozenge'a new coma
parisonis'done.If no node;xists to comparethe valuewith, the valueis insertedinto the tree as
new node,and an edgeis addedto connectit to the treo'
Appendix B Adavkion - lisualialon
& A.ination
First, we searchfor the
If the new nodecausesthe tree to be unbalanced,a rotationis animated.
the greenlozengemoves
orruaun""a .os-rr"". The blue lozengeis replacedby a gle€none,and
,rf tle tree ,rntit it nnasa nodewhosetreeis unbalancedlf oneis found' the usetis notifled of
greenlozwiich of the four rotationswill occur,andthe rctatio[ is done lf one is not found' the
engedisappears.
occu$'
In a rotation,whena nodemoves,the edgepointing to it is deletedbeforethe movement
pointsto it The only
After the nodehasassumedits new position,a llew edgeis drawnthat
the tre€'
exceptionto this actionis whenthe nodeis moving from or to the root position in
promptedfor the
After the valuehasbeeninsertedand arlynecessaryrotationdon9,the useris
next valugto insert into the tree.
Singleteft Fotafon
Figure8. FindingthePivotnode
Figure9. The balancedtree following a singleleft rotation
SPIaYTfe€ Rotation
'splay' demonstateszig-zig andzig-zagsplaytle€rctationsJhe user may view
Adavision's
'Run Animaeitherof the two rotationsasmanytimesass/hewould like by clicking XTANGO'S
tion' buttonandchoosingan option numberftom a shellwindow'
andthe
The zig-zagdemonstationincludesthre€nodesiX, theleft child of the pivot's right child
parent
node
of X'
the
nodeti belcessed; G, the original toot aodgrandparentnodeof X; andR
by iinks' to four triangularsuB-TreeslabelledA'B'C' andD' whereA
Th"." nod", ."
"onnected
is the left-mostsuB-TreeandD the right-mostsuB-Tree'
Appadix B Adavsion Vsu,liaiiot
& Aninaron
In viewing the zig-zaganimation,the links arerepositionedoneat a time andthe cor'esponding
lines of Aia codJ arehighlighteduntil the objectiveof makingX the new root of the tree is
accomplished.Following thi seriesof link movements,the imagesin the tree arercconstructed'
bringing the tree into its rotatedform.
similarly,exceptthatX is initially positionedasthe left child
The zig-zig rotationis demonstrated
of theDivot'sleft child.
. ZTC'ZTG-
SPLFY
ROTATION
nodeX'
of linksin orderto access
FisurelO.Themovement
. ztc-zlG'
SPLAY
ROTATION
*.---^------.:a
A
/
A
A
\
---^--=I
G
A\
a
,,\
A
'
A
'
t ] A
Figurell. The rotatedsplaytreewith X asits newroot
B-Tlee Algorithms
to
The following two Adavision animationsillushateinsertionsanddeletionson a B-Tree Due
oi tt B-Treealgorithm,theseanimationsdo IIot include the corespondingAda
tt e
"
is not nec"o-ptexltl
codeaspart o?fteir aisplays.Also dueto complexity'arldbecausethe implementation
implefi. *ft",,ft" -inLations are intendedto illustrate,the actualB-Trce algorithm is not
each
be
lnstead'
"*"ay
mentedinto oneof the two separateXTANGO files asit nomally would
performedon a particularBanimationmerely demonstra6sthe possibleactionsthat would be
Tree if an insertionor deletionwereto occul'
within eachof the B-Treeanimations,asa valueis inseltedor deleted,imageswhich represent
Appendir B Addision - visutliu tion & Aninajlon
pagell
are not relenodes,links andvaluesarerepositionedaccordingly Nodescontainingvalueslhat
by empty,smaller-sized'rectangular
vant io ttr" pu.ticuf* n-Tree demonstrationarerePresented
images,while nodescontainingvalueswhich arenecessaryfor the demonstrationare'epresented
by rion-empty,larger-sized,rectangularimages.The conditionof the particularB'Tree that is
showndependson the user'sresponseto a setiesof questionsregardingthe B-Treehe or she
would like to view. Thesequestionsare askedin the form of a dialoguebeforean animationis
theinsertionor deletionbeingpera labeldescribing
shown.Oncetheanimationis displayed,
formedis writtennearthebottomof theXTANGOwindow. Also,in theuppelleft comerof the
The B-Treedele*inao* ls u aispluyof text which indicatesthe valuebeinginsertedor deleted
tion animationadditionallyincludesa shorttextphrasewhichexplainswhatis occurringwithio
theB-Treeat lhe momentthattheimagesaremoving
B'Tree Insertion
four possiblewaysfor a valueto be insertedintoa BTheB-Treeinsertionanimationillustrates
intothe
Tree:into a non-fullleaf,a leafwhoseparentis non-full,whoseancestotis non-full'or
The
animais
split'
the
root
case
leafof a B-Trcewhichdoesnot Rtanyof thesecases,in which
into
which
he
thetypeof B-Tree
regarding
u aiufoguewhichaskstheuserquestions
tion
to theques"ontuint
on theuser'srcsponse
wouldlike to;ee an insertionPerformedDepending
or she
insertionsimulationis shown'
tions,the approPriate
is illustrated
Thecasein whichthevalue"l00" is insenedinto a leafwhoseparentis non-full
below.
Figure12.Theoriginalform of theB-Treeis displayed'
Appe.dix B Adavision visualianion & Aninalion
Figue 13.Thevalue"100"movcsdownthroughthetopof thefee'
Figure14.Thevalue" 100"movesdowntkoughtheparentnodc'
Appddii a Adtvisid - Vrsurlidion & Adtdion
pogp15
Figure15.Thevaluc"100" is inscrtedintoits conectplacein th€lcaf'
Figure 16.The midrtle valuc of the leaf,
Appadii B A&vfi@
'9O", movesup to the puent nodeandthe leaf is split'
- vlsualiadon & Adnttli@
Figure 17.The split nodes,alongwith their valuesandlinks, arerePositioned'
B-Tfee Deletion
The B-Treedeletionanimationillustratessix possiblewaysfor a valueto be deletedfrom a BTree:from a non-lcaf,a leaf that is laryerthanminimumsirc, a leaf whoseneighboris largerthan
minimumsiz€,whoseparcntis large!thanminimumsize' whoseancestoris lalger thanminimum
sizr, or a deletionfrom a B-Trco which do€snot fit anyof thesecases,in which c'se the root is
dissolved.similaltotheB-TEeinsertion,thisanimationcontainsadialogueofquestions.
Dependingon the user'sresponseto the questionsasked'the appropriatedeletionsimulatiol is
shown.Tie deletionof a valueftom the tre€is illustratedasthe valuomovesdown and into a
proceedsastheir
"garbagecan" image.The movementof rgmainingvalues,nodesalld links then
imagesarerepositionedaccordilgly
The casein which the value"100" is deletedftom a leaf whoseparentis largerthanthe minimum
siz€is illustratedbelow.
App€ndn B Ad.Vision - Visualizdon & Aninalion
Figure18.Thc originalfonn of theB-Treeis
DEl-aflOhtror LEAI. LErr fiInrhw'
lorH '€rcrcoRs r{tfl$n1. riiErlr Ntri tirnrfi$l
Figure19.Thevaluc"10o" is deletedby beingthlownintothc
Aooadi,i B Adav*ion-
ualizli@ & AIiET id
'!a$age can'
paF 18
oELEtloll Fto{ |EnF, ltAF Ilrrlll{ll,
roTH }]Erd€on5 ||rm|{fi, PAREHTor ftiltt'ttl
Figure20.Thevatue"50" is moveddownsothatth€leafmayr€gainits order'
DELElrorllid{ LEif, LEiF rllfitn$L
tltlrltllr'i. PnFEm||n talrllli.ll
BOTHNEIC'EORS
Figure 21. The leaf and its n€ighbormelge
Appcndix B adav6id
-
ualit"ai@ & Ariddd
!fi$
DETE Ofl rRd{ LEIF. LEiF ntuil}1.
mRE{T fiCr H rd
irllftu,
nElqEfls
asone'
Figurc22.Themergingnodes,theirlinks,andvalucsarerepositioned
Appendix B Adrviri@ - liludi4dd
& Anir|aliotr
pos.20
AppendixB
THREADS
Many experimentsthat areperformedin the laboratoriesinvolve runningtestson algorithmsthat
havebeenimplementedusingAda packagesThesetestsproducedresultsthat canbe measured
thechanceto be mo.edirectlyinvolvedin their
working in theIabgivesstudents
andanalyzed.
theyretarn'
leaming,increasilgtheamountof information
but mo'e areprovidedby
themselves,
will bewrittenby thestudents
Someof theAda packages
the instructor.In titis w;y, th€ studentsareexposedto more datastructuresandalgorithms Stutheeffectsof algorithmsinsteadof actually
dentswill spendtheirtime seeingandexperiencing
theirabilityto anaThis shouldincrease
datastructures.
codingthe algorithmsandconesponding
problem'
to
a
lyze the effeciivenessand,/orefficiencyof differentapproaches
areplannedfor thefollowingapplications:
Cunently,experiments
1) Big Oh Experiments
of differentsortingalgorithms
2) Comparison
3) Binary searchtlee vs AVL tree
4) Hashcollisionhandling
5) Big Oh coefficientevaluation
tool is needed
in a laboratorysetting,an appropriate
In orderto;n thesetypesofexperiments
of sucha tool, namedTHREADS'
of thedevelopment
The majorpartof our projectconsists
is a toolthatcanbe
on AdaDataStructures)
ExPeriments
THREADS(TestHamessfor Repetitive
type of the
user
some
algorithms,reportingback to the
usedto run tLstson datastructurcsand'black
and
separately'
thatareimplemgnted
box' programs
of thetest.The testsare
measurement
aswell.
maybe testedandrun separately
How th€StudentUsesTHIIEADS
by thefollowingchart
The basicideabehindTHREADSis illustrated
BlackBox
Data Set
THREADS
usedby a
THREADS generatesa datasetbasedon informationgivenby the user'This datasetis
bl-k bo* m--n on" uxperiment.Upon the black box's completion,it returnsto THREADS the
will be
samplesizeof the data;et andan integermgaswementof the test' The measurement
includedin a table that keepstrack of eachexperimentthe userruns'
RunningTHREADSbringsuptheinterfaceshowninFigure23.Allinfo'mationneededforthe
datase;s input in the appropriateplacesby the user'The parametersthe usel may designateare
asfollowsi
Method:The black box to usefor the experiment
Write to File; The namedfile wherethe datasst is stored'If no file is designated'a
temporarydefault file will be used.
Write Patir:The path to the directory whercall dataandfiles will be written'
UseFile: The path andnameof a datasetto be usedin placeof a file generatedby
THREADS.
SampleSize:The numberof elementsin the dataset'
Sam;le Distribution: lfte statisticalprobability distributionusedto generatedthe random
dataset.
SampleOrder:The extentof orderingimPosedon elomentsin the datasel'
generatedrandomlyfrom
The defauit seningsarefor a 100olement,completelyunsorteddataset
a uniformrandomdistribution.
Method
executesa black
ih" bl""k bo* pro""rs is spawnedby theTHREADS processWhenTHREADS
ITthenwaits for the black box to
box, it gives
'Wft"nth; black boi a datasetgeneratodby THREADS
tft" Ufu"kbox retums,THREADS takesthe dataandwrites it to the Tableof Mea."toin.
andthe secondis
r"*t"",". ift" Uf* box rotums2 intogers.The first is the sizeof the dataset
that the black box retums.
the measurement
retumedby the black box witl vary dependingon which black
The meaningof the measurement
may be the numberof comparisonsthat were
box is beingrun. In somecasesthe measurement
performedi-na sort routine.In the caseof the binary searchtre€exPerimgnts'the measurement
will be
depthof a nodein the tree.In all cases,however'the measurement
Loi"t"r" itt"
"u"."g"
or efficiencyof a.cenaindatastrucu ion-n"g"du" inr"g-"rusefulin analyzingtheeffectiveness
retumedfrom differentexpenments
ture or al-gorithmfoi a particulardaia set The measurements
canthen be comparedagainsteachother to aid the user'sanalysis'
write to File
the generated
th".o. fi"la l"b"t"d..write to File:', takesa nameasinput. If a nameis specified,
the "write Patlni'text
datasetwill be savedto a file with that nameill the dire'tory specifiedin
field. If no nameis specified,the datasetwill be savedto a temporaryfile'
Write Path
until a valid
th" "Wri pu,h," ,"*t field takesa patlt string asinput' THREADS will not operate
" The pathstring needsto be a pith wherethe userhasreadand write permissions'
Dathis siven.
not work
,""at i"a writeimany datafilei. If it cannotreadandwrite its data' it will
inni,iDi
without supplingthe write path' a noticeprompt
f.operty. f *re ,rseruttemptsto run a black box
AppendixB THREADS
will appearandnotify the userto supplyTHREADSwith the approp ate information.
ll6asur9|llen
Figure23
UseFile
The "Use File:" text fr€ld takesa string asinput, This text string mustcontainlhe enttue
path and nameof the datafite to be used.If a valid path andnameis given,THREADS
THRFADS will usea
will usethis datasetfor theblack box iNtead of generatinga new dataset
wishesto generatea new
sDecifieddatasetbeforegeneratinga new dataset'Therefore,if thc user
dala set,the string in the "UseFile" text field mustbe deleted'
SampleSize
data
The samplesizefield allows the userto enterthe numberof elementsto be ircluded irl the
to click on the
J, rangingfrom 1 to 10000.The samplesizemay be changedby ushg th€ mouse
is
upidow-nainows,or by manuallyenteringthe sizeinto the text field. The default 100elements.
in which the dataelementsareto be distribSampledistribution indicatesthe type of randomness
uted.Thereare six different distributionsto choosefrom'
1) Uniform.
2) Exponential.
3) Normal
4) Gamma
5) Poisson
6) Binomial
TotherightofthesampleDistribution,thereisabuttonlabeled.DistributionParameters'.Ifthis
buftoni;fcked a windowparelwith numberfieldswill appear(Figure24)'
(Figurc 24)
paramwith this distributionwindow panel,the usercanmodify the distdbutionsby changingthe
etersfor eachdistribution
data
Thesedistributionscanbe usedto evaluatehow the dist bution of datacanaffect different
distributioN
structures.For most cases,Uniform distributionis suffrcient-Futurework on
featureof
includesthe developmentof black boxesthat fully utilize the SampleDistribution
THREADS.
SampleOrder
like in thedatasetto be generated'
Thesampleorderrefersto thedegre€of ordertheuserwould
of thedatawill bein indeasthat 10070
---"i"" i.* -r oo . 100.A sampleorderof l0o meaIIS
sortedorder'
;pl" ord",of -t 00 t""ns that100%of fte datais in decreasing
#'#;;;;;
-100
between
vatue
Anv
il; ;i;;;'means thatthedatais in perfectlynndomorder'
^"#;;
e vatu"of so m"ansthatthefirst 5070of thedatais ir inqeasingsoded
;;i 06;r;;r;;bb.
is in randomorder'
order,theremainder
Data Set
andorder
i" g"n"rat"dbasedontheinformationfromthesamplesize'distribution'
ih".ro:t"
canalso
data
set
A
to fulfill theuser'srequirements
ar" randomlygenerated
nJia* ii" ""t
-use File;" textfieldby supplyinga pathandname.
"f",i*o
datasetusingthe
_^"'r...1i.p"*o
Table of Measurements
by theuser'experimeltsmayberspeatedThe
Si"* ail *" In"VUesavedin filosdesignated
mayalsobesaved'sotheusermavcomeback
session
from anexperimen-t
;;-";;;;;;""
re.ord.
r"", ,imeto continueanalysisor evenaddto thepreviousexperiment
a-,i" i""
'File'
monu'
"i " Uy
therightmousebuttonwhileonthetable Fromthe
iuites ure,au"A
:Suveas.L'anda savewindowwill appearToloadin a previouslysavedtable'
,t oo,lon "licking
" option'OPen'fromthe'File' menu'
"i*r"
the
choose
Run Exneriment
and.writtento theappronun n*p"timent' buttonis clicked,thedatasetis generated
ffilnG
andexecutedwhen theblackboxfinishes'the
is spawned
rl"i" nf'".n"-i, ,fti ulackboxprocess
lf theuserhasnotProi"."r" ti"" -J t"*turement ;re written'o thetableof measurements
information,theuserwill benotifiedto-dosoandno
;i h theappropriatc
il tiliGADitheuselwill benotifredthattherewas
*itt U" .n. ff th; bhck boxabortsor crashes,
"*o"ri*"nt
aninor in theblackbox andno datawilt bewriftento thetable'
View Graph
cunentlyin thetablewill beusedas
ffili-th" ii.* Gr"ph,buttonis clickod,thomeasuemenrs
'xvgr'
andmaybecreatedat anypointin
using
for a graph.Graphsarcgenerated
thecoorrtinates
iach graphis pioducedin its ownwindowwith a uniquetitle' which
sessio'-n.
theexperiment
graphs'
between
allowiforeasycomparison
Clear Table
a TI{READSsesThe'ClearTable'buttonallowstheuserto clearthetableatanyPoiotduring the 'ClearTable'
atanytime When
theuserto stana newsetofexperiments
sion.Thisenables
thetable lf "ClearTable"
Uuttonis ctickedapromptwill appearaskingif theyreallywantto cle.ar
theuserwill beretumedto THREADS
is selected,
If
i. ,"i."t"a. *r" tuft *iit t
"t"ut"a. "uncil
with no changes.
Coefficients
will appear(Figure25)'
ff th" Coeffrci"nts'bottonis clicked,a smallwindowwith fivebuttons
n'teing the sample size' If one
The five buttons are log(n), n, nlog(n), n2, and n to some power"
of that particular Big
of these buftons is clicied, an xterm will appeardisplaying the coefficients
We25
Oh of thedatain thetable.Forexample'if lhe datain thetableis:
600
100
If then2buttonis clicked,thextermwill apPardisplaying:
600 6.0000000008-02
100
Thismeansthatwith n=100andy={00, anetFessionof theformy=cnzwouldrequirec to be
overmanyvaluesof n, thefunction
eooooooog-oz.rr tns cocfncientremainsrelativelyconstant
for thebig-ohfirnctionof theblackboxProcess
is a goodcandidate
represented
Figure25
HeIo
'HelP' buttolon tle
window, or by pressing
Help-maybe found both by clicking the
IH-READ-S.
THRBADSwindow will opena pop-upwindow
the'helpiev on the keyboard.The buttonon the
'help'
key on the keyboad s'ill give a shortsumthat containscompletehelPtext. Pushingthe
mary of help for the spoton the window wher€the culsor is pointing'
aui!'quit'
askif dreuserreallywantsto quit'
buuonis clicked,a noticepromptwill appearamd
FG
ii can"e'iis setect"{ th" userwill beretumedto themainTHRBADSprogramwithoutary
Jtt-g"" ii ;q.it' it t"f*t a THREADSwill exit andcloseall windowsAlsowhenTIIREADS
fllesresrainin thesp€cifiedwritepath
it q.ir, Ai"rip"..V nleswill be deletedsono unwanted
directory.
THREADSTirtorial
progranis run a
th"r" i, *."11 tototialprograrnthatis includedwith THREADS'Whenthis
Appddir B fiRB,ADs
window opensthat displaysthe completetutorial text in a scrollablearea This window is sizedso
that it canie placedn;xt to the THREADS window on the samescreenfor easyreferencewhen
working with THREADS.
For theIrstructor
THREADS is composedof 1l fites anda Makefile.The nles andtheir contentsareasfollows:
Createdby the graPhicalinterfacecodegenerator,Devcuide 3'0 1'
threads.G:
Definitionsof labelsusedto receiveinformationaboutthe UIT objects'
threads-ui.h:
Setsup the interface,andbeginswaiting for eventsto process.
threads-ui.cc
threads-stubs.cc: Callbackfunctionsfor the vadouswidgetson the inlerface Also
containsany auxiliary functionsneededby THREADS.
Containsthe helptext retrievedby pressingthe "Help" key on the
thrcads.info:
keyboard.
Containsthe completehelPtext displayedin the THREADS help
longhelp.info:
window.
Containsthe graphicaldatafor the THREADS icon.
threads.icon:
Containsthe graphicaldatafor theTHREADS icon mask.
threads.mask
Containsthe preferencesfor xvgr.
xvgr.prefs:
Containsthe scriptthat is calledwhenonethe coefficientbuttonsare
coef.scpt:
clicked.
A very smallprogramthatjust waits until the userpressesthe Retum
Tet.cc:
key;usedin coef.scpt.
Black boxesmay be addedto THRBADS with little effort. The spotswhercthe codeneedsto be
modified are markedby commentsof the form:
*/
/* NEW METHODS: addany new methodshere
inserttheline:
First.in thofile threads-ui.cc,
("Method name")i
(void) mthdchoice.addchoice
'Method
name'is the nameto appearon the menuin the interface.For eachnew mgthod
where
added,a similar line mustbe inserted.Thg lines nesdto be addedto the currentlistitrg of choices,
which is markedin the code.
addaoother"elseif' conditionof the form:
Next, in the frle threads-stubs.cc,
elseif (strcmp(method,"MethodFile") : 0) {
"MethodName");
strcat(command,
I
,MethodFile' is the executablefile namefor the black box. Eachnew methodneeds
In this section
to haveits own casein the "if-else if' statement.
New methodscanalsobe usedby placingthemin the blackboxdirectory andtyping the nameof
.,Method:"text field. This is mucheasierfrom a programmingaspect,
the methodexecutablein the
but this requiresthe userto type in the nameinsteadof boing ableto selectit from the menu'
New typesof distributionsmay be addedin a sirnilar fashion-The menuchoicesfor "sample Distri-
'
of whai the distribution
bution arc addedthe sameway asthosefor "Method"' A cleardefitrition
the
meansandhow it will affect randomgenerationof integerswill facilitate the changesin
codeof threads-stubs.cc.
box aodto use
In threads-stubs.cc,the systemcalls useths full Pathnamesto exccutethe black
ttre other include nles. check that thesepalhsarc con€ct, andchangethem asapPropnate.
Appddit B THRBADS
pagc28
M'fueMm[&tu{Effial
40F4d!"-c D6's&ud(!5lth
lt,rrllal
!lg?29
DataStructures
Laboratory 1 - Writing an Ada program
1. Write an Ada programto acceptasinput an integern andto calculateandpdnt the nth
power of two (2n).Storeyour programin the nle r,AB1-1 . ADA.
Run your progtamfor somevaluesof n andverify that it is coffert. List the valuesand
resultsbelow:
Findtholargestintegorvalueof n for whichthisprogramgivesa corroctvalue'what is
thisvalueof n?
What happenswhenyou entera valuelargerthanthe abovevalue?
How many bits do you needto representthe largestvalueof 2n that Ada canrepresent?
Hint it takesk bits to represent2k - 1, andk+l bits to represent2k'
Do you think Ada can&presentintegersthat arelargerthanthe largestpossiblePowerof
2? Ii you are not sure,w;ite a little testprogramto sec.If so, what do you think would be
integer?
the largestrepresentable
Sinceyour computeralsohasto representnegativeintegers,andassumingit represents
useto
approiimately asmanynegativesaspositives,how ma(tybits doesyour machile
representinteger?
2. Modify the programyou wrote for #l to expressthe answerasfloat insteadof integer
Appcndix c D€fa slru.toe L.b M nal
type. store your modifiedprograurir the file r-lB1-2 ' ADA'
Run your programfor somevaluasofn ald verify that it is corect' List the valuesand
resultsbelow:
Findthc largostintegervalueof n for whichthisprogramgivesa corect value-what is
thisvalueof n?
What happ€nswhen you entcr a valuelargerthanthe abovevalue?
andtheexpoa floatingpointnumberin two parts,themantissa
Thecomputerr€present
uses!o reprenent.Fromyolrrrcsultsabove,howmrny digitsdo youthinkyollr comPuter
atEpossibl€aswell'
thatnegativeexponents
R€member
senttheexponent?
' Newton'smethodstartswith
3. Iffrite a programto useNewton'smethodto calculate^12
gucsses
using.rn* t = (tr -;)
successive
aninitial guess,x0,andtheng€nerates
guesses
arethesa$e
two consecutive
whenevcr
hasconverged
Con8id€rthattheProcess
or whenx2= 2. Foreachguesscalculatei$ errorasx2- 2.
How accualeis theanswerwhichyouobtain?Tohowmanyplacesis it accuratc?
How doesyour answerhererelateto your answerto #2?
Appodir C Dna Stu.tu6 blt Mdurr
psge3l
Data Structures
Laboratory2 - UsingAda Packages
In this laboratory,you will solvethe sametwo problemsyou solvedin Laboramryl' but you will
that you will useare
makeuseof Ada packagesto enhanceyour solutions The two Ada Packages
describedbelow:
whichpermitsyouto do arithmeticon iltegerswith infiis a Package
big-inceger
Package
nite prlcision. You are thercfolenot limited to the sizeof integersimplementgdon the machine
that you areusing.A full setof adthmeticoperatorsareimplementedin this packagefor datatype
is
of thePackage
big-inL. The specification
big-integer
. ads
Note: It is reconmended chac this package be used with
implementation that uses automatic garbage collection'
package big-inteqer
b!'pe big-i.nt
an Ada
is
is Private;
procedure pub(a : big-int);
procedure get(a : out biq-inc);
function nbi(s : sEring) leEurn big-int;
: inEeger := 0) return big-int;
function nbi(i
-- noi stands for "Make Big Inceger"
procedure dbi{a : in out big-int);
function bi2int(a : big-int) return inteqer;
function
"+'(a, b : big-int) return big-inl;
return big-int;
"+"(a : big-int)
'-"(a, b : big-inE) return big-inL;
teturn big-int;
"-"(a : biq-int)
"*,1a, b : big-inE) return big-int;
"/" \a, b : big-int) return big-int;
"rem"(a, b : bj-g_int) return blg-int;
div(a, b: biq-iat; result,
remainder : in out big-int);
"abs"{a : big-int) return bjg-inE;
function
function
function
"<" (a, b : big-int)
"q=" 1a, b : big-int)
";'"(a, b : big-int)
function
function
furrction
function
function
function
function
procedure
App€DdixC Dala Strctus
bb Mmual
retuln boolean;
return boolean;
retuln boolean;
page32
ret\rrn boolean;
function (>=" (a, b : big-int)
function equal(a, b : big-int ) return boolean;
-- This is not the same as Ltre operator "="'
-- When making arithnetic
comparisons for equality,
the above funcLion.
b : integer) return
function equal{a : big-int;
return floatt
: big-int)
function asfloat(a
return bigr-int;
function "mod"(a, b : big-int)
: exceplion;
big-int-error
use
boolean;
pravate
tl4)e digit-node,
is access digit-node;
tl.pe drlJtr
is
tlrpe digit-node
record
d : integer range 0..9;
next : dnitr;
end record;
is
big-int
record
r boolean;
is3os
'
dnitr;
dl
record,
end
end big-integer;
tlpe
Belowis anexampleprogramwhichusesthetypebigint.Thisprogramshouldserveasa pattem
for the progmmsyou needto wdto in this andtho following laborato es:
--
Program
co compute
che square
use text-io;
with text-io;
packase in!-io
is new inteser-io
u
s
e
inl-io;
wilh int-io;
use tex!-io;
wiLh Eexl-io;
use big-integer,
\,rith big-integer;
procedure
square
nutnber
lab2-examp]e
: biqr-int
: it':Leger;
of
an integet
( inleerer
and Etore
an'l print
as a bj'gint
),
is
:= mbi{1);
begin
set(nunber);
-- nbi converts
to biqint'
intese!'
,= nlci {number ) *niri (nutnber ) ;
;ql]"t"
-- this calls
puE from package biq-inleger'
end 1ab2-exa$P1e;
app.ndrr C Dal!S@duEs Ltb Mtuutl
'
l. Rewdtettle programyou usedin Laboratory1 to calculatepowers-of2, using tyPebig-int
insteadof integerior the calculations.Calculate2 to the powersl 16,1023' 1024'and2M8'
Verify that the first 16 powersof 2 arecorrectfrom the answersobtainedin l'aboratory l'
What aresomeways that you canspotcheckthe answersto 21023and2102?
How manydigitsarctherein 2104?How manyin 22s8?How manywouldyou expectin 24096?
Another package that is provided is one that does calculations for rational numbers. A lational
For
number ii a number that is representedby two integers, a numerator and a denominator'
I
example, the float number 0.5 would be representedby the two integers ( I ,2) since it is equal to 1 '
The specification of the package rat-pack defining tyPe rational is
Package
tl'pe
Rat-Pack
Rati.onal
is
is
Private;
return Ratj.onaf ;
function
"+" (R1,R2:Rational)
function
"-" (R1.R2:Ratioltal) return RationaL;
'
function
" * (R1, R2 : Rational ) return Rational;
function
"/" (R1,R2:Rational) return Rational;
function Rat (11,12: integer) return Rational;
-- converts
to a rational
Ewo integers
Numer (R: Rational ) return ltrEeger;
function
nuj'ber
-- returns
the o\rmerator of a rational
inceger;
Denoft (R: Rational ) recurn
function
nuniber
-- returns
of a rational_
the denominator
boolean;
function
"<" (R1, R2 ; Rational ) return
return boolean;
function
">" (R1,R2:Rational)
procedule
Put (R:Rational),
-- oueputs a rational
nunber
Value (R: Rational ) r:eturn float;
function
to a rational
- reLurns
approximation
a ftoat
zero Denominator
: excepElon;
App.ndrx C Dda StNcluRs ljb M&ual
number
--
raised when a rational
denoninator
operator
lesulbs
in a zero
private
tt4 e Rauional is record
Nuln : intege!;
Den : integer;
enil record;
end Rat-Pack;
squareroot of two using Newlon's
2, Using the PackagelatJack, rep€atthc calculationof the
mpthod.
of digits ir thEd$ominator' that canbe
What is the bcst aPproximahon,mcasulpdby thc number
getreratcdusing tYPerational?
possibleusingfloat?
to thcb€stapproximation
IIow doesthiscompatE
Whatis exceptionis laiserlwhenyourprogramis terminatcd?
Why wasthis exceptionraisedby youl Pro$am8t thistime?
Appddn c DarasttucfG
tib Mdoal
pagp35
minateyour calculationafter the seventhestimate.
What is the accuracythat you obtainedon the seventhestimate?
Next we introducethe following genericpackage:
--
ratgen. ads
--
This is
tl4)e
Multiple
--
nunlcers over tlte
a qeneric package to define rational
i-nttl4)e .
operabors on inttl4)e are passed as par'lmeters '
generic
boolean;
as Prlvalet
return ioetlpe;
: inttlPe)
"+"(i1,i2
'-"(i1,i2
: i.nttl'pe) return intt)/pei
\-'(i1
return inttl1)e;
: inttlpe)
"*" (il-,i2 : inttl'pe) return inttl4)e;
retuln 1ntts)'pe;
: inttlpe)
"/' (i7'f2
return inttype;
inttype)
:
"ren"(i1,i2
: inttl@e) return booLean;
equal(il-,i2
: inttlT)e, i2 : integer) return
intequal{il
inttype
function
function
function
function
function
funcgion
function
function
tt4)e
with
with
with
with
with
with
with
with
: inttlpe) return boolean;
with function "<"(i1,i2
width : integer := 1000;
: inttlFe;
with procedure put(il
base :
with function asfloat(i1
package rat-gen rs
tl4te racional is Priwate;
function "+'lr!,
-- sum of
function '+'(11
-- identity
functiolt "+"(r1
-- adds a
funccion "+" (il--
functjon
-function
-function
-function
integer := 10);
return
: inttlpe)
float'
12: rational) return rationali
two rationals
: rational) return rational;
operator
i1 : inttl4re) return
: rational;
rational to an inttyPe
leturn
: inttlGte; 11 : rational)
adds an intlt)4)e fo a lational
retuln raLional;
rational)
"-" lrI, 12:
rationals
of two
difference
return rational;
(r1
rational)
:
"-"
negation operator
return
i1 : inttl'pe)
"-" (r1 : rational;
from rational
inttl4)e
subtracts
'-"(i1
return
11 : rational)
: inttlFe;
ADpodir C Dlta Slructm tj!
Mdu,r
rational;
rational;
ratj-onal;
rational;
-- subtracts rational
from inttl'pe
reeurn rational;
12 : rational)
function '*"(r1.
-- Product of two rationals
function s*' (rl- : r:ational; i1 : intt)Pe) leturn
-- multiplies
rational bY inttl|tr)e
retur:n
11 : rational)
: inttft)e;
function "*'{i1
-- nultiplies
inttlrpe by rational
/
'
\
l
.
l
,
12: rational) return rallional;
function
-- quotient of two rationals
return
i1 : inttlpe)
: rational;
function "/"(r1
-- divides rational bY anttl4)e
return
: inttl.pe; 11 | rational)
function {/"(i1
-- divides intt]'Pe bY ratj-onal
return rational;
i2 : inttlpe)
function rat(i1,
j'I/i2
-- creates rational
ouL of two inttypes
function nr.rmer(r : rabional) return lnttltpe;
r
-_ returns the numerator of the rational
leturn intLype;
function denom(r : rational)
r
-- leturns the denominator of the rational
function "a"111, r2 : rational) reeurn boolean;
-_ less than comparison for two rationals
return booleant
function ">" lr!, t2 : rational)
_- greater than conparison for two rationals
procedure Put(r : rational ) ;
-- output function for rational
return float;
function value(r : rational)
-- eonvergs raEional to real
zero-denominator
rational;
rational;
ratlonal;
rational;
: exceptaon;
private
is
t]4)e rational
record
num : 1n!E)4)e;
den : inttlT)e;
end recordt
end
rat_gen;
root of 2 esti.
2. Using rat-gen with inttype dennedasinteget rerunyour programfor the square
mation.
Why did this fail to obtain the accuracythat you obtainedin #l ?
What causedthe Processto fail.
3. Finally, apply the typebig-integer to the generictype rat-gen to obtain
Appddir C Dat, ShcrurcsLlb Mdual
'ationals over the
big-integer type. Run your squarercot of two progam usingthis dstatype andobservethe
estimate.
I€sults.Onceagain,terminareyour prc$am after the seYetrth
How doesthe sevsnlhostimal€comparcwith tlre s€vonlhestimateyou obtainedio #l?
of usinga sinple
ovcrth€approach
do you seeto usingthisgqedc approach
Whatadvantage
typ€in #l ?
Appodn C Dat! Sti!.n6s Irb M4@t
Data Structures
Laboratory 4 - Big Oh SamPling
repoltedftom
andexaminingmeasuremgnts
Threadsis a tool for runningexperimeltalprograms
usingThrcadssoftware'
This laboratoryis yourfirstexperience
thoseprograms.
of this software'
ReadtheThreadshelpfile andfamiliarizeyourselfwith thecapabilities
thobehaviorof variousbig-ohralosusingThroads'
Fivepm$amsareprovidedfor youto observe
2nusinganalgorithmwhichis O(logn)' Runthispro1.LaM-l is a programwhichcomputes
andgraphtheresultingdataForeachvalueof n' run
gramttrioughmreiaasforn=64,128'256'512
threedatapointsat eachvalueof n'
threetimes!o generaie
ihe exoeriment
Comparethegraphof yourdatawith theglaphof thelogarithmfunctiorlThebcstwayto do this
to a straightlinc' The
theresulting€mPh
is to ptot ttrislraitr usingtheLog-linearaxes.Compare
nearerthis apiroximatesastraightline,thc nearcryourtimesar€to O(logn)' Re'ordbelowthe
thegraph'
conceming
andyourobservations
datatablegenerated
Appadii C Daia sh@lls
lib Mmu.l
2.Lab42is ^prcgr.'1lwhichsumsthefirst n integers.It shouldrunwith a timeof O(n)'Runit
andpdnt yourtableandgraph'
for n=50'100,150,200,250,
;ith tlueerepetitions
,rt
"eltTh*"i
Recordyourdatatablein thespacebclow:
a straightline if thetimeof this algorithmis actuallyO(!) Does
Yourgraphshouldapproximate
it appoarto apFoximatea straightline?
2i for i=l,..,n.It shouldhavea runnin€titncof O(n log
3. Lab4-3is a Fogramwhichcalculates
and
for n= 50, 100'150,200'250'300'
with threerepetitions
tbrcugh'Ihreads
n). Runlhisp;g;
rccordyourtableof restiltsbelow:
plot on Log-log axes'
GraDhthe tableof valuesgenerated'Changeyour graphof the abovedatato
case?
If this ls truty O(n log n) time, this graphshouldappearasa sraight line' Is this the
Appddix C Data SEstuc
bb Moutl
It
in I
4. Lab4-4 is a progalrl which calculatesa multiplicationtabtefor all paifs of integers "n'
shouldrun with a time of o(n2). Run it throughThreadswith tbreerepetitionsfor n=50,
100,150,200andcopy your table valuesbelow;
graph
Changeyour graphof the aboved4tato plot on Lpglog axes rf this i8 truly O(n') time, this
you
the
slope?
estimate
do
strouli aipeaiara st.aight line with slopetwo. Is this the case?How
additions'It doesthis very
2nvia repeated
5. Lab4-5 is a programwhichrccursivelycalculatas
poorlyfrom a bigoh pointof viewandrunswith a timQof O(2n)'Belaus€this algorithmhasa
with threerep€titionsfor n=10,11'12'13
iin-tirne whichlrowi vcry rapidly,runthroughThreads
by 1' Record
doubleseverytimen is increased
and14.Noticethattheru;-timeapproximstely
yourtablevaluesbelow:
Changeyour graphof the abovedalato plot on Linear-logaxes'If this is truly O(2tr) time' this
grapb,shouldappearasa straightline. Is lhis the case?
ApD.nds C Dala ShdG
t2b Mdul
afterrgflectingontheresultsof thefive teststhatyouhaverun.
6. Answerthefollowitrgquestions
In whichcases
agreeto thorcsultsthalyouexpeeted?
did theresultsyouobtained
Howaccurately
andwhichcasestheleast?
wastheageementthegreatest
thc cxp€ctcdrcsultsandthe
between
mighttherebcfor thediscrepancy
Whatexplanations
observed
rEsultsin thes€experiments?
is
How do youexplainthevariancc,if any,in thetimesreportedwhenthesameexperiment
repeated
severaltimes?
App@dsc DrtastnmG L:b Meual
paec4l
Data Structures
Laboratory 5 - Big Oh Determination
This labontory rcquircsyou to analyzelO differenttestproglamsto determinethe big-oh of the
runningtime. You will f,rst be askedto determinothe runnilg time by analyzingthe codefor the
function and thenyou arc to verify your hypothesisby usingThreads.A usefulfact for working
with logarithmsin this lab is the following identity thatcar be usedto convertlogs from basea to
baseb:
.
roe'"=
function Testl (n: integer ) feturn
count : integer: =0;
newn : integer: =n/2;
begin
while newn>o foop
.^rrnt-
. =^^1lnt-+
toz^n
@i
integer
is
1 !
newnt=nevrn/2;
end loop;
what is the runningtimc for this function in big-oh notation?Justify your answer
Howdoesthisverify or conaadictyour
Showresultsftom running0is functiorthroughThreads.
previousanswer?
if rccessary.
Hint: try n=1,2,3,4,5,6,7,8
andse€if any
Changeyourhypothesis
pattememerges
thatis helpful.
ADMdir C Data structu@ tib Mdual
Test2 (n: integer)
function
count : integer: =0;
newn : integer: =n;
begin
white neun>0 loop
cor.mt : =count+1;
newn:=newn-l;
end loop;
reEurn counE;
end Test2;
return
ineeqer
is
wlrat is the running time for this functionin big-ohnotation?Justify your answer'
showrssultsfrom runningthisfunctionthroughTheads.Howdocsthis velify or contradictyour
if nec€ssary
Chang€yourhyPothesis
pEviousanswer?
function
arMdn
Tesu3 (!r: integer)
C D6ra$rctug
trb M@u.r
return
integer
is
cou4t : integer: =0;
begin
for i in 1..n looP
count: =count+Test1 (n) t
end loop;
recurn count;
end Test3;
What i6 the runningtimo for this function in big-oh notation?Justify your answer.
Howdoesthisvgriryor contndictyour
ShowrcsultsfromrunningthisfunctionthrcughThreads.
if necessary
previousanswer?
Changeyourhypothesis
Test4 (n: integer)
function
count : integer: =0 t
Appcrdii C Daia $tuctG
kb M@ual
return
integer
is
begin
for j- in 1.-n looP
colmt: =count+Test2 (B) ;
end loop;
return count;
end Test4;
What is the running time for this function in big-oh notation?Justify your answer.
Howdoesthisveriryor conhadictyour
Showresultsftom runningttrisfunctionthmughThreads.
if nccessary
previousanswer?Changeyourhypothesis
Tests (n: integer)
function
count : j.nteger: =0;
begin
ApFldii
C tu
Si.lduq
bb Mdu.l
return
inleger
is
fo! i in 1.-n loop
courrt: =count+Test4 (n) ;
end loop;
recurn counE;
end Test5;
What is the running time for this functionin big-oh notatiol? Justify your answer.
Howdoesthis vedfyor contradictyour
Showresultsfrom runningthisfunctionthroughThreads.
if necEssary
previousanswer?Chang!yourhypothesis
functsion
^^''-r-
newn
begin
Test6 (n: integer)
intAdar.=n:
; integer: =!/2;
ApFndn C tu! sirud|s LabMeu.t
return
inbeger
i5
while neltrr>o loop
count:=counu+test1(n)
rrewn: =newn/ 2 ;
end loop;
;
end Test6;
What is the runningtime for this function in big-oh notation?Justify your aNwer.
Caution:don'ttry to run this with n
Showrcsultsftom ruBningthis functionthroughThreads.
Changeyourhypothegr€alorthan20.How doesthis verifyor contadictyourpreviousanswer?
sisif nec€Esary
return
TestT (n: integier)
function
count : inLeger: =0;
begin
if n>0 then
count: =count+test7 (!-1) +1;
App@dix C Dala St ndu6 t b M@od
intseger
is
!4ge49
else
count : =0;
end if;
return count;
end TesgT;
What is the runniry time for this functionin big-ohnotation?Justiry your answcr.
Howdoesthisveriryor contradictyour
Showrcsultsfrom runningthisfunctionthroughThrcads.
if nccessary
F€viousanswer?Changeyourhypothesis
return intege!
TestS (n: i4teger)
function
count : ineeger: =0;
nelvn : integef: =n;
begin
if n>0 then
count: =count+testg (n-L ) +Eestg (n-1) ;
,{@ndir C Dab St udl@ hb Mau.r
is
pag.50
else
count: =1;
end if;
return count;
end TeseS;
What is the runningtime for this futrctionin big-oh notati'on?Justi$ your answer
Showrcsultsftom runningthisfunctionthroughTh€ads.Ho}l'doesthisvedfyor contadictyour
if nepessary
previousanswet?Changeyourhypothesis
return
fu.nction Testg (n: integer)
=0
t
count : integer:
begin
if n>1 then
counL: =count+test9 (n/2 ) +1;
else
count: =0;
ApFdn C Darsstru@
Lrb Meutl
inceger
j-s
end if;
recurn count;
end Bestg;
What is the ru,nningtfunefor this &mctionin big.ot| nofafion?Justify your answet
IIow doesthisYerifyor corltadictyour
Showrcsullsftom runningthisfimctioathrc4b Threads.
previou answc(?Chsngeyourhypob€sisif o€c€ssa'ry
A9p@dr C Drr. SlrudhtrErLltb M!!'El
p6€p52
DataStructures
Laboratory 6 - Stacksand Queues
For this laboratoryyou will be introducedto algorithmanimation ln orderto do this we will use
the specialsoftwaxcpackagecalledXTango.
1. Run Xlango for the PostOffice simulation.In orderto do this you needto type the command
/ csci286 /xtango/anims /post
/]nori.e
program'
In this case,we simulatea Postoffico with n servingstations,wheren is an input to the
the 25 customA simulationis thenrun ani you will be askedto observethetotal waiting time for
ersthat ale served.The file that containsthe aniYaltimesthat you will useis
/hone/csci2 85 /Po . dat.
Recordthe total waiting timesin the tablebelow:
Number of Stations
Total Wait Time
I
2
3
4
In otherwords,afterthequeue
what is thelimit in thesiz€of queueallowedin thissimulation?
no longgrenterthesystemWhatis thatsizo?
a certainsize,customers
rgaches
Did vou notice arv inefficienciesin the way the queueingsystemsworks?What
thatis. with lesstoralwail time?
maketheoueuesoperatemoreemciently,
App.ndix C Data SlrudJA
lab Mdual
could be doneto
3. The Ada program for converting a string from infix to postfix form is given below:
while
not
dar-
if
end_of_iBput
/havf
clmh^l
I
loop
.
operand (next_syrnbol ) then
hrli-
lhavi-
crhh^-l
I
' ) ' then
elsif
next,stanbol=
while top(stack /='('loop
hrrf
/h^h
lcf:^L\
\
.
end foop;
pop (stack) ;
eI s e
while not Empty(stack) and then
<= Priority
Priority(next*s\anbot)
if top (stack) /=')'
then
nrr F /n^^/cF.^L\
anA
if
(top ( stack) ) loop
\
.
end loop;
hrl
c}l
/navi-
end if;
end loop;
lvhile not
h,'t
rh^h
clm}\^l
I
empty(stack)
/ cf
--L
\ \
loop
.
end loop;
Theprioritiesusedfor theoperands
in thisalgodthmarcgivenin thefollowingtable:
Operand
(
+ -
Priority
2
I
0
In this algorithm,get meansgot the nextcharacterftom the input streamandput meansput the
next characterto the output stream.Pushandpop refer to operationson a separatestack.
Run the XTangoanimationfor this programby typing
/ho e / csci286 / xtango/anims /postfix
Run this for the input streama+bto seehow the algorithmoperates.
arehandled,run XTangofof the inPutstrearna+(b*c).
To seehow parentheses
To seehow priodty is used,run XTangofor the input streamsa+b*c and a*b+cand
Make up a complexexpressionthat containsat least5 operatorsandusesboth parentheses
priodty. Write your expressio[in the spaceblow:
App€ndix C Dall Skuctu€s bb Mdual
Run throughthe algorithmby ha[d ad F€diot tho psttlting ouFut saeatnbelow:
Now ruo thealgodthnin Xlango andvedryyourresult.
Agpddn C De $rufiGr L.b Mrnu.l
Data Structures
Laboratory 7 - Comparisonof AYL and BST
youwill beusingTHREADSto comparctheuseof AVL treesandBinary
For this laboratory,
Searchtreeswithoutbalancitg.Ttvoproglamsareprovidodin theMethodmenuof THREADS
whichyouwill usefo. thislab.TheyareTbstAVLandTestBST.
Theyretumtherotaldepthof all
of thenodesin a binarysearchfteewith X nodesgenerated
at random.
l. RunTesESTto generate
binarysearchtre€sfor samplesizes100,200,400,800,1600,3200.
Run
theexpcrimcntthre€timesfor eachsamplesize.
(a)Ent€rthevaluesyouobtainedb€low
(b) Make a graphof the valuesyou obtained.Doosthe graphlook linear?
(c)Now we will perfonna moresophisticatcd
testfor lin€arity,usiBgthe"Coefficients"buttonon
THREADS.Generate
thecoefficients
for n, nlogn,andpower.Whatconclusions
do youdraw
from yourresultsasto thegrowthlateof thetotaldepthof all nodesin a randombinarysearch
ttee?
Apladir
C Dala Srmct@ lr!
Meuat
2. Now repeattheaboveexpedm€ltfor TestAvL.Firstclearoutyourtablein THREADS,then
rerunall of theexperiments.
(a)Writeyourresultsbelow:
Howdo youexplain
O) Howdothesevaluescomparewith thevaluesyouobtaincdfor TestBST?
thiscomparison?
(c) Runyourdatathrough"Coeffrcient"agafufor n, nlogn,andpower.How doesthiscompare
for TestBsT?
with whatyouobseryed
App.trda C DaE Sm|l:lrc
bb Meu.l
.
3. Now we'rc going to placethe entriesin the hee in all odercd fashiol That is' we arc going to
insqt into the tlee from smallestto largcst.You setthe ord€rby changing"SampleOdef in
THREADS to 100.GlOo woutd do the same,but placathe valuesin descendingorder.)Do this
andreruntlre experimelts for TestAvl.
(a) Entcr the r€sultsbelow:
(b) Usecoefficicntsto obscrvethegrowthrateof thisdata.Whatdo youobserve?
Thistime,limit yoursamplesizesto 100'200,400'
4. Now rcpeatthesameploc€ssfor TestBST.
and800.
(a)Repottyourresultsbelow:
Hon'doyouexplainthis?
O) Useco€fficientsto observcthegrowthrat€.what do youobserve?
(c) Why did I not haveyou rull this experimentfor samplesiz'es$eater than 800?
ADHda
c Dlh Srrcr6
r2b Mdual
5. Now try thesamsexperiment
with thesaryle onlypartiallyorderedYoucandothis if youset
SampleOrderto 20.ThismoansthatthefiIst 20%of thesampleis in orderandtheremainder
is
randonLNow reruntheexperiment
in 4 usingthisordering.
(a) Repodyourresultsbelow:
(b)UseCoeffrcients
to estimatethggrowlhrate.Whatdo yous€eandwhatis yourestimale?
(c) Whathavcyouleamedfromthisentirelaborstory?
AppordixC Dr|! Sirud'G rlb M6url
p.Ce59
DataStructures
Laboratory8 - Sort ComParisons
For this laboratory,you will be usingTHRBADSto comparevarioussoding methods-The five
sort mothodsthat we will comparcars Merye Sort,ShellSort,HeapSort, Quicksort,andInsertions Sort.
l. Run Sortl, Merge SoIt, andobservetheelapsedtime for Sortilg 1,000to l0'000 valuesin steps
of 1,000.
(a) Enler the timo for 10,000b€low;
(b) This sort is Merye Sort which is supposcdto be an n log n sort.Usethe Co€fficientbuttonof
Theads to testthis hypothesis.Are the valuesyou obtainfairly stable?Do you concludethat your
observationsaren log n?
(c) Now rerunthosortsfor samplesize10,000,butuscordereddata.Whatwasthetime thatyou
in (a)?
overthetimeobserved
Is this animprovement
for 10,000?
observed
order = (d) FinaUy,run Sortl for 10,000samplesizewith thevaluesin rcverseorder(SamPle
in (a)and(c)?
100).How doesthis comPaleto thetimesobserved
Agpadix c D!r! stm.nq
I:b Meual
2. Run Sort2,Shell Sort, andobservethe elapsedtime for sorting 1,000to lO,0O0valuesin steps
of 1.000.
(a) Enter the time for 10,000trelow:
(b) This sort is Shell Sort which hasan undereminedbig Oh. Us€the Coefficientbuttonof
Threadsto makean hypothesisaboutits big Oh. What would bc your bestestimaie?
(c) Now rerunthesortsfor samplesize10,000,butuseordereddataWhatwasthetimethatyou
observed
for 10,000?
Is thisanimprovemeot
overthetimeobservcd
in (a)?
(d) Finally,run Sort2for 10,000samplesizewith thevaluesin rcverseorder(SampleOrder= 100).How doesthiscompare
to thetimesobserved
in (a)and(c)?
A@dn
C Drn! SIructUB kh Maual
3. RunSod3,HeapSort,andobservetheelapsed
timefor sorting1,000to 10,000valuesitr sieps
of 1.000.
(a) Enter the time for 10,000 below:
(b) Thissortis HeapSortwhichis supposod
to beann log n sort.UsetheCoefficientbuttonof
Threadsto testthishypothesis.
Are thevaluosyouobtainfairly stable?
Do youconcludethatyour
aren log n?
observations
(c) Now rerunthe sortsfor samplesize 10,000,but useordereddata.What wasthe time that you
observedfor 10,000?Is this an improvementover the time observedin (a)?
(d) Finally, run Sort3for 10,000sampl€sizewith the valuesin reverscorder(SampleOrder= 100).How doesthis comparcto the timesobservedin (a) and (c)?
Appddix C Dar! Struc{G tlb Meu.t
timefor sorting1,000to 10'000valuesin steps
4. RunSort4Quicksort,andobservetbeelapsed
of 1,000.
(a)Enterthotimefor 10,000below:
log ll sort Usc the Coofficientbutton of
O) This sort is Quicksortwhich is supposedto be ann
your
to tt"t Oit ttypotlesis. AIe thevaluesyou obtainfairly stable?Do you concludethat
ftrt
"a"
aren log n?
observations
butus€ordercddala Whatwasthetimethatyou
(c) Now rerunthesortsfor samplesiz€l0,OO0,
in (a)?
overthetimeobserved
for t0,000?Is thisanimprcvcment
observed
Order= (d) Finally,run Sod4for 10,000samplesizewith thevaluesin rcvels€order(SamPle
in (a)and(c)?
itio). ttow aocsOis conparcto thetimesobscrved
ApFadncDltrstuctrBt
blrdual
pag.63
5. Rutr Soft5,INertion sort aIld observethe elapsedtime for sottiog 1,000to 5,000valuesin
stepsof 1,000.The reasonthat we use5,000instoadof 10,000will becomeobvious.
(a) Enter the time for 5,0ff below:
to beannzsort.Usetbc Coefficientbuttonof
O) This sortis InsertionSortwhichis suppos€d
Do youconcludsthatyour
Arethevaluesyouobtainfairty stable?
Thrcadsto testthishypothesis,
obscrvations
aren2?
(c)Now rsrunthesortsfor samplesizes1,000to 10,000,butusoordereddata.Whatwasthetime
in (aX
for 5,000?Is thisaninprovemcntover0retimeobserved
thalyouobscrved
(d) Fina y, run SorBfor 5,000samplesizewiih thevaluesin revers€order(SampleOrder= 100).How doesthis comparcto thetimesobsewedin (a) and(c)?Do youhaveanyexplanation
for this?
ApFodir C Dlb Sl'wtEr
trb Msul
Download