learn data structures and algorithms with golang level up ... · discovered clojure in early 2009,...
TRANSCRIPT
![Page 1: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/1.jpg)
![Page 2: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/2.jpg)
LearnDataStructuresandAlgorithmswithGolang
LevelupyourGoprogrammingskillstodevelopfasterandmoreefficientcodeBhagvanKommadi
BIRMINGHAM-MUMBAI
![Page 3: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/3.jpg)
![Page 4: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/4.jpg)
LearnDataStructuresandAlgorithmswithGolang
Copyright©2019PacktPublishingAllrightsreserved.Nopartofthisbookmaybereproduced,storedinaretrievalsystem,ortransmittedinanyformorbyanymeans,withoutthepriorwrittenpermissionofthepublisher,exceptinthecaseofbriefquotationsembeddedincriticalarticlesorreviews.Everyefforthasbeenmadeinthepreparationofthisbooktoensuretheaccuracyoftheinformationpresented.However,theinformationcontainedinthisbookissoldwithoutwarranty,eitherexpressorimplied.Neithertheauthor,norPacktPublishingoritsdealersanddistributors,willbeheldliableforanydamagescausedorallegedtohavebeencauseddirectlyorindirectlybythisbook.PacktPublishinghasendeavoredtoprovidetrademarkinformationaboutallofthecompaniesandproductsmentionedinthisbookbytheappropriateuseofcapitals.However,PacktPublishingcannotguaranteetheaccuracyofthisinformation.CommissioningEditor:RichaTripathiAcquisitionEditor:ShahnishKhanContentDevelopmentEditor:ZeeyanPinheiroTechnicalEditor:KetanKambleCopyEditor:SafisEditingProjectCoordinator:VaidehiSawantProofreader: SafisEditingIndexer:TejalDaruwaleSoniGraphics:AlishonMendonsaProductionCoordinator:DeepikaNaik
Firstpublished:March2019
Productionreference:1290319PublishedbyPacktPublishingLtd.LiveryPlace35LiveryStreetBirminghamB32PB,UK.ISBN978-1-78961-850-1
www.packtpub.com
![Page 5: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/5.jpg)
mapt.io
Maptisanonlinedigitallibrarythatgivesyoufullaccesstoover5,000booksandvideos,aswellasindustryleadingtoolstohelpyouplanyourpersonaldevelopmentandadvanceyourcareer.Formoreinformation,pleasevisitourwebsite.
![Page 6: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/6.jpg)
Whysubscribe?SpendlesstimelearningandmoretimecodingwithpracticaleBooksandVideosfromover4,000industryprofessionalsImproveyourlearningwithSkillPlansbuiltespeciallyforyouGetafreeeBookorvideoeverymonthMaptisfullysearchableCopyandpaste,print,andbookmarkcontent
![Page 7: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/7.jpg)
Packt.com
DidyouknowthatPacktofferseBookversionsofeverybookpublished,withPDFandePubfilesavailable?YoucanupgradetotheeBookversionatwww.packt.comandasaprintbookcustomer,youareentitledtoadiscountontheeBookcopy.Getintouchwithusatcustomercare@packtpub.com formoredetails.Atwww.packt.com,youcanalsoreadacollectionoffreetechnicalarticles,signupforarangeoffreenewsletters,andreceiveexclusivediscountsandoffersonPacktbooksandeBooks.
![Page 8: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/8.jpg)
Contributors
![Page 9: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/9.jpg)
AbouttheauthorBhagvanKommadi,thefounderofQuanticaComputacaoandArchitectCorner,hasaround18years'experienceintheindustry,rangingfromlarge-scaleenterprisedevelopmenttoincubatingsoftwareproductstartups.Hehasamaster'sdegreeinIndustrialSystemsEngineeringfromtheGeorgiaInstituteofTechnology(1997)andabachelor'sdegreeinAerospaceEngineeringfromtheIITMadras(1993). HeisamemberoftheIFXforumandanindividualmemberofOracleJCP.HehasdevelopedGo-basedblockchainsolutionsintheretail,education,banking,andfinancialservicesectors.Hehasexperienceofbuildinghigh-transactionalapplicationsusingJava,Python,Go,Ruby,andJavaScriptframeworks.
![Page 10: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/10.jpg)
AboutthereviewerEduardBondarenkoisasoftwaredeveloperlivinginKiev,Ukraine.HestartedprogrammingusingBasiconaZXSpectrummany,manyyearsago.Later,heworkedinthewebdevelopmentdomain.HehasusedRubyonRailsforover8years.HavingusedRubyforalongtime,hediscoveredClojureinearly2009,andlikedthesimplicityofthelanguage.BesidesRubyandClojure,heisinterestedinGoandReasonMLdevelopment.Iwanttothankmywonderfulwife,mychildren,andmyparentsforallthelove,support,andhelptheyhavegivenme.
![Page 11: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/11.jpg)
WhatthisbookcoversChapter1,DataStructuresandAlgorithms,focusesonthedefinitionofabstractdatatypes,classifyingdatastructuresintolinear,non-linear,homogeneous,heterogeneous,anddynamictypes.Abstractdatatypes,suchascontainer,list,set,map,graph,stack,andqueue,arepresentedinthischapter.Thischapteralsocoverstheperformanceanalysisofdatastructures,aswellasthecorrectchoiceofdatastructuresandstructuraldesignpatterns.Chapter2,GettingStartedwithGoforDataStructuresandAlgorithms,coversGo-specificdatastructures,suchasarrays,slices,two-dimensionalslices,maps,structs,andchannels.Variadicfunctions,deferredfunctioncalls,andpanicandrecoveroperationsareintroduced.Slicingoperations,suchasenlargingusingappendandcopy,assigningparts,appendingaslice,andappendingpartofaslice,arealsopresentedinthischapter.Chapter3,LinearDataStructures,coverslineardatastructuressuchaslists,sets,tuples,stacks,andheaps.Theoperationsrelatedtothesetypes,includinginsertion,deletion,updating,reversing,andmergingareshownwithvariouscodesamples.Inthischapter,wepresentthecomplexityanalysisofvariousdatastructureoperationsthatdisplayaccessing,search,insertion,anddeletiontimes.Chapter4,Non-LinearDataStructures,coversnon-lineardatastructures,suchastrees,tables,containers,andhashfunctions.Treetypes,includingbinarytree,binarysearchtree,T-tree,treap,symboltable,B-tree,andB+tree,areexplainedwithcodeexamplesandcomplexityanalysis.Hashfunctiondatastructuresarepresented,alongwithexamplesincryptographyforavarietyofscenarios,suchasopenaddressing,linearprobing,universalhashing,anddoublehashing.Chapter5,HomogeneousDataStructures,covershomogeneousdatastructuressuchastwo-dimensionalandmulti-dimensionalarrays.Arrayshapes,types,literals,printing,construction,indexing,modification,transformation,andviewsarepresentedtogetherwithcodeexamplesandperformanceanalysis.Matrixrepresentation,multiplication,addition,subtraction,inversion,andtransposescenariosareshowntodemonstratetheusageofmulti-dimensionalarrays.Chapter6,HeterogeneousDataStructures,coversheterogeneousdatastructures,suchaslinkedlists,ordered,andunorderedlists.Wepresentthesinglylinkedlist,doublylinkedlist,andcircularlinkedlist,alongwithcodesamplesandefficiencyanalysis.OrderedandunorderedlistsfromHTML3.0areshowntodemonstratetheusageoflistsandstoragemanagement.
![Page 12: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/12.jpg)
Chapter7,DynamicDataStructures,coversdynamicdatastructures,suchasdictionaries,TreeSets,andsequences.SynchronizedTreeSetsandmutableTreeSetsarecoveredinthischapteralongwithGocodeexhibits.SequencetypesincludingFarey,Fibonacci,look-and-say,andThue-Morse,arediscussedwithGoprograms.Thischapteralsoexplainstheusageanti-patternsofdictionaries,TreeSets,andsequences.Chapter8,ClassicAlgorithms,coverspre-order,post-order,in-order,level-ordertreetraversalsandlinkedlisttraversals.Sortingalgorithms,suchasbubble,selection,insertion,shell,merge,andquickareexplainedwithcodeexhibits.Searchalgorithms,aswellaslinear,sequential,binary,andinterpolationmethods,arealsocoveredinthischapter.Recursionandhashingareshownbymeansofcodesamples.Chapter9,NetworkandSparseMatrixRepresentation,coversdatastructuressuchasgraphsandlistsoflists.Differentusecasesfromreal-lifeapplications,suchassocialnetworkrepresentation,maplayouts,andknowledgecatalogs,areshownwithcodeexamplesandefficiencyanalysis. Chapter10,MemoryManagement,coversdynamicdatastructures,suchasAVLtreesandstackframes.Garbagecollection,cachemanagement,andspaceallocationalgorithmsarepresentedwithcodesamplesandefficiencyanalysis.Garbagecollectionalgorithms,suchassimple/deferred/one-bit/weightedreferencecounting,markandsweep,andgenerationalcollection,areexplainedwithananalysisoftheiradvantagesanddisadvantages.Appendix,NextSteps,shares thelearningoutcomesforthereaderarisingfromthebook.Thecoderepositorylinksandkeytakeawaysarepresented.Referencesareincludedforthelatestdatastructuresandalgorithms.Tipsandtechniquesareprovidedtokeepyourselfupdatedwiththelatestondatastructuresandalgorithms.
![Page 13: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/13.jpg)
Packtissearchingforauthorslikeyou
Ifyou'reinterestedinbecominganauthorforPackt,pleasevisitauthors.packtpub.comandapplytoday.Wehaveworkedwiththousandsofdevelopersandtechprofessionals,justlikeyou,tohelpthemsharetheirinsightwiththeglobaltechcommunity.Youcanmakeageneralapplication,applyforaspecifichottopicthatwearerecruitinganauthorfor,orsubmityourownidea.
![Page 14: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/14.jpg)
TableofContentsTitlePageCopyrightandCredits
LearnDataStructuresandAlgorithmswithGolangAboutPackt
Whysubscribe?Packt.com
ContributorsAbouttheauthorAboutthereviewerPacktissearchingforauthorslikeyou
PrefaceWhothisbookisforWhatthisbookcoversTogetthemostoutofthisbook
DownloadtheexamplecodefilesDownloadthecolorimagesConventionsused
GetintouchReviews
6. Section1:IntroductiontoDataStructuresandAlgorithmsandtheGoLanguage
7. DataStructuresandAlgorithmsTechnicalrequirementsClassificationofdatastructuresandstructuraldesignpatterns
ClassificationofdatastructuresListsTuplesHeaps
StructuraldesignpatternsAdapterBridge
drawShapemethoddrawContourmethod
CompositeDecoratorFacadeFlyweightPrivateclassdataProxy
RepresentationofalgorithmsFlowchart
![Page 15: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/15.jpg)
PseudocodeComplexityandperformanceanalysis
ComplexityanalysisofalgorithmsBigOnotationLinearcomplexityQuadraticcomplexityCubiccomplexityLogarithmiccomplexity
BruteforcealgorithmsDivideandconqueralgorithmsBacktrackingalgorithmsSummaryQuestionsandexercisesFurtherreading
8. GettingStartedwithGoforDataStructuresandAlgorithmsTechnicalrequirementsArraysSlices
Thelenfunction Slicefunction
Two-dimensionalslicesMapsDatabaseoperations
TheGetCustomermethodTheInsertCustomermethod
VariadicfunctionsTheupdateoperationThedeleteoperation
CRUDwebformsThedeferandpanicstatements
TheInsertCustomermethodTheUpdateCustomermethodTheDeleteCustomermethod
CRMwebapplicationTheCreatefunctionTheInsertfunctionTheAlterfunctionTheUpdatefunctionTheDeletefunctionThemainmethod
TheHeadertemplateTheFootertemplateTheMenutemplateTheCreatetemplate
![Page 16: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/16.jpg)
TheUpdatetemplateTheViewtemplate
SummaryQuestionsFurtherreading
9. Section2:BasicDataStructuresandAlgorithmsusingGo10. LinearDataStructures
TechnicalrequirementsLists
LinkedListTheNodeclassTheLinkedListclass
TheAddToHeadmethodTheIterateListmethodTheLastNodemethodTheAddToEndmethodTheNodeWithValuemethodTheAddAftermethodThemainmethod
DoublylinkedlistTheNodeBetweenValuesmethodTheAddToHeadmethodAddAftermethodTheAddToEndmethodThemainmethod
SetsTheAddElementmethodTheDeleteElementmethodTheContainsElementmethodThemainmethod–containselementTheInterSectmethodTheUnionmethodThemainmethod–intersectionandunion
TuplesQueues
TheNewmethodTheAddmethodThemainmethod–queuesSynchronizedqueue
TheNewmethodTheStartTicketIssuemethod TheEndTicketIssuemethodTheticketIssuemethodTheStartPassmethod
![Page 17: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/17.jpg)
TheEndPassmethodThepassengermethodThemainmethod
StacksTheNewmethodThePushmethodThePopmethodThemainmethod
SummaryQuestionsFurtherreading
11. Non-LinearDataStructuresTechnicalrequirementsTrees
BinarysearchtreeTheBinarySearchTreeclass
TheInsertElementmethodTheinsertTreeNodemethodTheinOrderTraversemethodTheinOrderTraverseTreemethodThePreOrderTraverseTreemethodThepreOrderTraverseTreemethodThePostOrderTraverseTreemethodThepostOrderTraverseTreemethodTheMinNodemethodTheMaxNodemethodTheSearchNodemethodThesearchNodemethodTheRemoveNodemethodTheremoveNodemethodTheStringmethodThestringifymethodThemainmethod
Adelson,Velski,andLandis(AVL)treeTheKeyValueinterfaceTheTreeNodeclass
TheoppositemethodThesingleRotationmethodThedoubleRotationmethodTheadjustBalancemethodTheBalanceTreemethodTheinsertRNodemethodTheInsertNodemethodTheRemoveNodemethod
![Page 18: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/18.jpg)
TheremoveBalancemethodTheremoveRNodemethodThemainmethod
B+treeB-treeT-tree
TablesTheTableclassTheRowclassTheColumnclassTheprintTablemethodThemainmethod
SymboltablesContainers
CircularlinkedlistThehashfunctionsSummaryQuestionsFurtherreading
12. HomogeneousDataStructuresTechnicalrequirementsTwo-dimensionalarrays
RowmatrixColumnmatrixLowertriangularmatrixUppertriangularmatrixNullmatrixIdentitymatrixSymmetricmatrixBasic2Dmatrixoperations
TheaddmethodThesubtractmethodThemultiplymethodThetransposemethodThedeterminantmethodTheinversemethod
Zig-zagmatrixSpiralmatrixBooleanmatrix
TheprintMatrix methodThemainmethod
Multi-dimensionalarraysTensors
Summary
![Page 19: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/19.jpg)
QuestionsFurtherreading
13. HeterogeneousDataStructuresTechnicalrequirementsLinkedlists
SinglylinkedlistsTheCreateLinkedListmethodTheReverseLinkedListmethodThemainmethod
DoublylinkedlistsCircular-linkedlists
TheCircularQueueclassTheNewQueuemethodTheIsUnUsedmethodTheIsCompletemethodTheAddmethodTheMoveOneStepmethodThemainmethod
OrderedlistsTheToStringmethodTheSortByAgetypeTheThingclass
TheByFactorfunctiontypeTheSortmethod
ThingsorterclassThelen,swap,andlessmethodsThemainmethod
ThestructtypeThemultiSorterclass
TheSortmethodTheOrderBymethodThelenmethodTheSwapmethodThelessmethodThemainmethod
UnorderedlistsTheUnOrderedListclass
TheAddtoHeadmethodTheIterateListmethodThemainmethod
SummaryQuestionsFurtherreading
14. DynamicDataStructures
![Page 20: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/20.jpg)
TechnicalrequirementsDictionaries
DictValtypeDictionaryclass
PutmethodRemovemethodContainsmethodFindmethodResetmethodNumberOfElementsmethodGetKeysmethodGetValuesmethodThemainmethod
TreeSetsInsertTreeNodemethodDeletemethodInOrderTraverseTreemethodTheinOrderTraverseTreemethodPreOrderTraverseTreemethodThepreOrderTraverseTreemethodSearchmethodTheStringmethodThemainmethodSynchronizedTreeSetsMutable TreeSets
RemoveNodemethodTreeset.bst
SequencesFareysequence
StringmethodTheg methodThemainmethod
FibonaccisequenceFibonacciNumbermethodMainmethod
Look-and-sayThue–Morse
SummaryQuestionsFurtherreading
15. ClassicAlgorithmsTechnicalrequirementsSorting
Bubble
![Page 21: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/21.jpg)
SelectionTheswapmethodThemainmethod
InsertionInsertionSortermethodThemainmethod
ShellThepowermethodThemainmethod
MergeMergeSortermethodJoinArraysmethodThemainmethod
QuickThedividePartsmethodTheswapmethodThemainmethod
SearchingLinearBinaryInterpolation
RecursionHashing
TheCreateHashMutliplemethodThe XORmethodThemainmethod
SummaryQuestionsFurtherreading
16. Section3:AdvancedDataStructuresandAlgorithmsusingGo17. NetworkandSparseMatrixRepresentation
TechnicalrequirementsNetworkrepresentationusinggraphs
TheLinkclassTheNewSocialGraphmethodTheAddLinkmethodThePrintLinksmethodThemainmethodTest
RepresentingasocialnetworkTheNewSocialGraphmethodTheAddEntitymethodTheAddLinkmethodThePrintLinksmethod
![Page 22: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/22.jpg)
ThemainmethodMaplayouts
TheMapLayoutclassTheNewMapLayoutmethodTheAddPlacemethodTheAddLinkmethod ThePrintLinksmethodThemainmethodTest
KnowledgegraphsTheKnowledgeGraphclass
TheNewKnowledgeGraphmethodTheAddClassmethodTheAddLinkmethodThePrintLinksmethodThemainmethodTest
SparsematrixrepresentationusingalistoflistsSparseMatrixclass
TheShapemethodTheNumNonZeromethodTheLessThanmethodTheEqualmethodTheGetValuemethodTheSetValuemethodTheNewSparseMatrixmethodThemainmethod
SummaryQuestionsFurtherreading
18. MemoryManagementTechnicalrequirementsGarbagecollection
TheReferenceCounterclassThenewReferenceCountermethod
TheStackclassTheStackclass–anewmethodThemainmethod
ReferencecountingSimplereferencecountingDeferredreferencecountingOne-bitreferencecountingWeightedreferencecounting
Themark-and-sweepalgorithm
![Page 23: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/23.jpg)
ThegenerationalcollectionalgorithmCachemanagement
TheCacheObjectclassTheIfExpiredmethod
TheCacheclassTheNewCachemethodTheGetObjectmethodTheSetValuemethod
ThemainmethodSpaceallocation
PointersTheaddOnemethodThemainmethod
Concepts– GomemorymanagementProfiling
SummaryQuestionsFurtherreading
NextStepsTechnicalrequirementsLearningoutcomes
KeytakeawaysNextsteps
Chapter1–DataStructuresandAlgorithmsChapter2–GettingStartedwithGoforDataStructures and AlgorithmsChapter3–LinearDataStructuresChapter4–Non-LinearDataStructuresChapter5–HomogeneousDataStructuresChapter6–HeterogeneousDataStructuresChapter7–Dynamic DataStructuresChapter8– ClassicAlgorithmsChapter9–NetworkandSparseMatrixRepresentationChapter10–MemoryManagement
TipsandtechniquesUsingchannelwithatimeoutintervalUsingcontextinsteadofchannelLoggingwiththelinenumberGotoolusageGoenvironmentvariablesTesttableImportingpackagesPanic,defer,andrecover
OtherBooksYouMayEnjoy
![Page 25: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/25.jpg)
PrefaceLearnDataStructuresandAlgorithmswithGocoverstopicsrelatedtosimpleandadvancedconceptsincomputerprogramming.Theprimaryobjectiveistochoosethecorrectalgorithmanddatastructuresforaproblem.Thisbookexplainstheconceptsforcomparingalgorithmcomplexityanddatastructuresintermsofcodeperformanceandefficiency.Golanghasbeenthebuzzwordforthelasttwoyears,withtremendousimprovementsbeingseeninthisarea.ManydevelopersandorganizationsareslowlymigratingtoGolang,adoptingitsfast,lightweight,andinbuiltconcurrencyfeatures.Thismeansweneedtohaveasolidfoundationindatastructuresandalgorithmswiththisgrowinglanguage.
![Page 26: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/26.jpg)
WhothisbookisforThiscomprehensivebookisfordeveloperswhowanttounderstandhowtoselectthebestdatastructuresandalgorithmsthatwillhelptosolvespecificproblems.SomebasicknowledgeofGoprogrammingwouldbeanaddedadvantage.Thisbookisforanyonewhowantstolearnhowtowriteefficientprogramsandusetheproperdatastructuresandalgorithms.
![Page 27: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/27.jpg)
TogetthemostoutofthisbookTheknowledgeweassumeisbasicprogramminginalanguageandmathematicalskillsrelatedtotopicsincludingmatrices,setoperations,andstatisticalconcepts.Thereadershouldhavetheabilitytowritepseudocodebasedonaflowchartoraspecifiedalgorithm.Writingfunctionalcode,testing,followingguidelines,andbuildingacomplexprojectintheGolanguagearetheprerequisitesthatweassumeintermsofreaderskills.
![Page 28: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/28.jpg)
DownloadtheexamplecodefilesYoucandownloadtheexamplecodefilesforthisbookfromyouraccountatwww.packt.com.Ifyoupurchasedthisbookelsewhere,youcanvisitwww.packt.com/supportandregistertohavethefilesemaileddirectlytoyou.Youcandownloadthecodefilesbyfollowingthesesteps:
1. Loginorregisteratwww.packt.com.2. SelecttheSUPPORTtab.3. ClickonCodeDownloads&Errata.4. EnterthenameofthebookintheSearchboxandfollowtheonscreeninstructions.
Oncethefileisdownloaded,pleasemakesurethatyouunziporextractthefolderusingthelatestversionof:
WinRAR/7-ZipforWindowsZipeg/iZip/UnRarXforMac7-Zip/PeaZipforLinux
ThecodebundleforthebookisalsohostedonGitHubathttps://github.com/PacktPublishing/Learn-Data-Structures-and-Algorithms-with-Golang. Incasethere'sanupdatetothecode,itwillbeupdatedontheexistingGitHubrepository.Wealsohaveothercodebundlesfromourrichcatalogofbooksandvideosavailableathttps://github.com/PacktPublishing/.Checkthemout!
![Page 29: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/29.jpg)
DownloadthecolorimagesWealsoprovideaPDFfilethathascolorimagesofthescreenshots/diagramsusedinthisbook.Youcandownloadithere:http://www.packtpub.com/sites/default/files/downloads/9781789618501_ColorImages.pdf.
![Page 30: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/30.jpg)
Conventionsused
Thereareanumberoftextconventionsusedthroughoutthisbook.CodeInText:Indicatescodewordsintext,databasetablenames,foldernames,filenames,fileextensions,pathnames,dummyURLs,userinput,andTwitterhandles.Hereisanexample:"Let'stakealookatthe len functioninthenextsection."Ablockofcodeissetasfollows:
//mainpackagehasexamplesshown//inHands-OnDataStructuresandalgorithmswithGobookpackagemain
//importingfmtpackageimport("fmt")//mainmethodfuncmain(){fmt.Println("HelloWorld")}
Anycommand-lineinputoroutputiswrittenasfollows:gobuild
./hello_world
Bold:Indicatesanewterm,animportantword,orwordsthatyouseeonscreen.
Warningsorimportantnotesappearlikethis.Tipsandtricksappearlikethis.
![Page 31: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/31.jpg)
Getintouch
Feedbackfromourreadersisalwayswelcome.Generalfeedback:Ifyouhavequestionsaboutanyaspectofthisbook,mentionthebooktitleinthesubjectofyourmessageand [email protected]:Althoughwehavetakeneverycaretoensuretheaccuracyofourcontent,mistakesdohappen.Ifyouhavefoundamistakeinthisbook,wewouldbegratefulifyouwouldreportthistous.Pleasevisitwww.packt.com/submit-errata,selectingyourbook,clickingontheErrataSubmissionFormlink,andenteringthedetails.Piracy:Ifyoucomeacrossanyillegalcopiesofourworksinanyformontheinternet,wewouldbegratefulifyouwouldprovideuswiththelocationaddressorwebsitename.Pleasecontactusatcopyright@packt.comwithalinktothematerial.Ifyouareinterestedinbecominganauthor:Ifthereisatopicthatyouhaveexpertisein,andyouareinterestedineitherwritingorcontributingtoabook,pleasevisitauthors.packtpub.com.
![Page 32: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/32.jpg)
ReviewsPleaseleaveareview.Onceyouhavereadandusedthisbook,whynotleaveareviewonthesitethatyoupurchaseditfrom?Potentialreaderscanthenseeanduseyourunbiasedopiniontomakepurchasedecisions,weatPacktcanunderstandwhatyouthinkaboutourproducts,andourauthorscanseeyourfeedbackontheirbook.Thankyou!FormoreinformationaboutPackt,pleasevisit packt.com.
![Page 33: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/33.jpg)
Section1:IntroductiontoDataStructuresandAlgorithmsandtheGoLanguageWewillbeintroducingtheabstractdatatypes,definition,andclassificationofdatastructures.Readerswillbewell-versedwithperformanceanalysisofalgorithmsandchoosingappropriatedatastructuresforstructuraldesignpatternsafterreadingthispart.Thissectioncontainsthefollowingchapters:
Chapter1,DataStructuresandAlgorithmsChapter2, GettingStartedwithGoforDataStructuresandAlgorithms
![Page 34: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/34.jpg)
DataStructuresandAlgorithmsAdatastructureistheorganizationofdatatoreducethestoragespaceusedandtoreducethedifficultywhileperformingdifferenttasks.Datastructuresareusedtohandleandworkwithlargeamountsofdatainvariousfields,suchasdatabasemanagementandinternetindexingservices.Inthischapter,wewillfocusonthedefinitionofabstractdatatypes,classifyingdatastructuresintolinear,nonlinear,homogeneous,heterogeneous,anddynamictypes.Abstractdatatypes,suchas Container,List,Set,Map,Graph,Stack,andQueue, arepresentedinthischapter. We willalsocovertheperformanceanalysisofdatastructures,choosingtherightdatastructures,andstructuraldesignpatterns.ThereadercanstartwritingbasicalgorithmsusingtherightdatastructuresinGo. Givenaproblem,choosingthedatastructureanddifferentalgorithmswillbethefirststep.Afterthis,doingperformanceanalysisisthenextstep.Timeandspaceanalysisfordifferentalgorithmshelpscomparethemandhelpsyouchoosetheoptimalone. ItisessentialtohavebasicknowledgeofGotogetstarted.Inthischapter,wewillcoverthefollowingtopics:
ClassificationofdatastructuresandstructuraldesignpatternsRepresentationofalgorithmsComplexityandperformanceanalysisBruteforcealgorithmsDivideandconqueralgorithmsBacktrackingalgorithms
![Page 35: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/35.jpg)
TechnicalrequirementsInstallGoversion1.10from https://golang.org/doc/install foryouroperatingsystem. ThecodefilesforthischaptercanbefoundatthefollowingGitHubURL: https://github.com/PacktPublishing/Learn-Data-Structures-and-Algorithms-with-Golang/tree/master/Chapter01.ChecktheinstallationofGobyrunningthehelloworldprogram athttps://github.com/PacktPublishing/Learn-Data-Structures-and-Algorithms-with-Golang/tree/master/hello_world:
//mainpackagehasexamplesshown//inHands-OnDataStructuresandalgorithmswithGobookpackagemain
//importingfmtpackageimport("fmt")//mainmethodfuncmain(){fmt.Println("HelloWorld")}
Runthefollowingcommands:gobuild
./hello_world
Thefollowingscreenshotdisplaystheoutput:
![Page 36: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/36.jpg)
Let'stakealookattheclassificationofdatastructuresandstructuraldesignpatternsinthenextsection.
![Page 37: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/37.jpg)
ClassificationofdatastructuresandstructuraldesignpatternsYoucanchooseadatastructurebyusingclassification. Inthissection,wediscussdatastructureclassificationindetail.Thedesignpatternsrelatedtothedatastructurearecoveredaftertheclassification.Inthenextsection,we'lltakealookatclassificationofdatastructures.
![Page 38: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/38.jpg)
ClassificationofdatastructuresThetermdatastructurereferstotheorganizationofdatainacomputer'smemory,inordertoretrieveitquicklyforprocessing.Itisaschemefordataorganizationtodecouplethefunctionaldefinitionofadatastructurefromitsimplementation.Adatastructureischosenbasedontheproblemtypeandtheoperationsperformedonthedata.Ifthesituationrequiresvariousdatatypeswithinadatastructure,wecanchooseheterogeneousdatastructures. Linked,ordered,andunorderedlistsaregroupedasheterogeneousdatastructures. Lineardatastructuresarelists,sets,tuples,queues,stacks,andheaps.Trees,tables,andcontainersarecategorizedasnonlineardatastructures.Two-dimensionalandmultidimensionalarraysaregroupedashomogeneousdatastructures.Dynamicdatastructuresaredictionaries,treesets,andsequences.TheclassificationofDataStructuresisshowinthefollowingdiagram:
![Page 39: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/39.jpg)
Let'stakealookatlists,tuplesandheapsinthenextsections.
![Page 40: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/40.jpg)
ListsAlistisasequenceofelements.Eachelementcanbeconnectedtoanotherwithalinkinaforwardorbackwarddirection.Theelementcanhaveotherpayloadproperties.Thisdatastructureisabasictypeofcontainer.Listshaveavariablelengthanddevelopercanremoveoraddelementsmore easilythananarray.Dataitemswithinalistneednotbecontiguousinmemoryorondisk.Linkedlistswereproposedby AllenNewell,CliffShaw,andHerbertA.SimonatRANDCorporation.Togetstarted,alistcanbeusedinGo,asshowninthefollowingexample;elementsareaddedthroughthe PushBackmethodonthelist,whichisinthe container/listpackage:
//mainpackagehasexamplesshown//inHands-OnDataStructuresandalgorithmswithGobookpackagemain
//importingfmtandcontainerlistpackagesimport("fmt""container/list")
//mainmethodfuncmain(){varintListlist.ListintList.PushBack(11)intList.PushBack(23)intList.PushBack(34)
forelement:=intList.Front();element!=nil;element=element.Next(){fmt.Println(element.Value.(int))}}
Thelistisiteratedthroughthe forloop,andtheelement'svalueisaccessedthroughtheValuemethod.Runthefollowingcommands:
gorunlist.go
Thefollowingscreenshotdisplaystheoutput:
![Page 41: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/41.jpg)
Let'stakealookatTuplesinthenextsection.
![Page 42: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/42.jpg)
TuplesAtupleisafinitesortedlistofelements.It isadatastructurethatgroupsdata. Tuplesaretypicallyimmutablesequentialcollections.Theelementhasrelatedfieldsofdifferentdatatypes.Theonlywaytomodifyatupleistochangethefields.Operatorssuchas+and*canbeappliedtotuples.Adatabaserecordisreferredtoasatuple.Inthefollowingexample,powerseriesofintegersarecalculatedandthesquareandcubeoftheintegerisreturnedasatuple:
//mainpackagehasexamplesshown//inHands-OnDataStructuresandalgorithmswithGobookpackagemain
//importingfmtpackageimport("fmt"
)//getsthepowerseriesofintegeraandreturnstupleofsquareofa//andcubeofafuncpowerSeries(aint)(int,int){
returna*a,a*a*a
}
ThemainmethodcallsthepowerSeriesmethodwith3asaparameter. Thesquareandcube valuesarereturnedfromthemethod:
//mainmethodfuncmain(){
varsquareintvarcubeintsquare,cube=powerSeries(3)
fmt.Println("Square",square,"Cube",cube)
}
Runthefollowingcommands:goruntuples.go
![Page 43: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/43.jpg)
Thefollowingscreenshotdisplaystheoutput:
ThetuplescanbenamedinthepowerSeriesfunction,asshowninthefollowingcode:
funcpowerSeries(aint)(squareint,cubeint){
square=a*a
cube=square*a
return
}
Ifthereisanerror,itcanbepassedwithtuples,asshowninthefollowingcode:
funcpowerSeries(aint)(int,int,error){
square=a*a
cube=square*a
returnsquare,cube,nil
}
![Page 44: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/44.jpg)
HeapsAheapisadatastructurethatisbasedontheheapproperty.Theheapdatastructureisusedinselection,graph,andk-waymergealgorithms.Operationssuchasfinding,merging,insertion,keychanges,anddeletingareperformedonheaps.Heapsarepartofthe container/heap packageinGo.Accordingtotheheaporder(maximumheap)property,thevaluestoredateachnodeisgreaterthanorequaltoitschildren.Iftheorderisdescending,itisreferredtoasamaximumheap;otherwise,it'saminimumheap.TheheapdatastructurewasproposedbyJ.W.J.Williamsin1964foraheapsortingalgorithm.Itisnotasorteddatastructure,butpartiallyordered.Thefollowingexampleshowshowtousethecontainer/heappackagetocreateaheapdatastructure:
//mainpackagehasexamplesshown//inHands-OnDataStructuresandalgorithmswithGobookpackagemain
//importingfmtpackageandcontainer/heapimport("container/heap""fmt")//integerHeapatypetypeIntegerHeap[]int
//IntegerHeapmethod-getsthelengthofintegerHeapfunc(iheapIntegerHeap)Len()int{returnlen(iheap)}
//IntegerHeapmethod-checksifelementofiindexislessthanjindexfunc(iheapIntegerHeap)Less(i,jint)bool{returniheap[i]<iheap[j]}//IntegerHeapmethod-swapstheelementofitojindexfunc(iheapIntegerHeap)Swap(i,jint){iheap[i],iheap[j]=iheap[j],iheap[i]}
IntegerHeaphasaPushmethodthatpushestheitemwiththeinterface://IntegerHeapmethod-pushestheitemfunc(iheap*IntegerHeap)Push(heapintfinterface{}){
*iheap=append(*iheap,heapintf.(int))}//IntegerHeapmethod-popstheitemfromtheheapfunc(iheap*IntegerHeap)Pop()interface{}{
![Page 45: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/45.jpg)
func(iheap*IntegerHeap)Pop()interface{}{
varnintvarx1intvarpreviousIntegerHeap=*iheapn=len(previous)x1=previous[n-1]*iheap=previous[0:n-1]returnx1}
//mainmethodfuncmain(){varintHeap*IntegerHeap=&IntegerHeap{1,4,5}
heap.Init(intHeap)heap.Push(intHeap,2)fmt.Printf("minimum:%d\n",(*intHeap)[0])forintHeap.Len()>0{fmt.Printf("%d\n",heap.Pop(intHeap))}}
Runthefollowingcommands:gorunheap.go
Thefollowingscreenshotdisplaystheoutput:
Let'stakealookatstructuraldesignpatternsinthenextsection
![Page 46: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/46.jpg)
StructuraldesignpatternsStructuraldesignpatternsdescribetherelationshipsbetweentheentities.Theyareusedtoformlargestructuresusingclassesandobjects.Thesepatternsareusedtocreateasystemwithdifferentsystemblocksinaflexiblemanner. Adapter,bridge,composite,decorator,facade,flyweight,privateclassdata,andproxyaretheGangofFour(GoF)structuraldesignpatterns. Theprivateclassdatadesignpatternistheotherdesignpatterncoveredinthissection.Wewilltakealookatadapterandbridgedesignpatternsinthenextsections.
![Page 47: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/47.jpg)
AdapterTheadapterpatternprovidesawrapperwithaninterfacerequiredbytheAPIclienttolinkincompatibletypesandactasatranslatorbetweenthetwotypes.Theadapterusestheinterfaceofaclasstobeaclasswithanothercompatibleinterface.Whenrequirementschange,therearescenarioswhereclassfunctionalityneedstobechangedbecauseofincompatibleinterfaces.Thedependencyinversionprinciplecanbeadheredtobyusingtheadapterpattern,whenaclassdefinesitsowninterfacetothenextlevelmoduleinterfaceimplementedbyanadapterclass.Delegationistheotherprincipleusedbytheadapterpattern.Multipleformatshandlingsource-to-destinationtransformationsarethescenarioswheretheadapterpatternisapplied.Theadapterpatterncomprisesthetarget,adaptee,adapter,andclient:
Targetistheinterfacethattheclientcallsandinvokesmethodsontheadapterandadaptee.Theclientwantstheincompatibleinterfaceimplementedbytheadapter.Theadaptertranslatestheincompatibleinterfaceoftheadapteeintoaninterfacethattheclientwants.
Let'ssayyouhavean IProcessor interfacewithaprocessmethod,the Adapter classimplementstheprocessmethodandhasan Adaptee instanceasanattribute.TheAdapteeclasshasaconvertmethodandan adapterTypeinstancevariable.ThedeveloperwhileusingtheAPIclientcallstheprocessinterfacemethod toinvokeconvertonAdaptee.Thecodeisasfollows:
//mainpackagehasexamplesshown//inHands-OnDataStructuresandalgorithmswithGobookpackagemain//importingfmtpackageimport("fmt")//IProcessinterfacetypeIProcessinterface{process()}//AdapterstructtypeAdapterstruct{adapteeAdaptee}
TheAdapterclasshasa process methodthatinvokesthe convertmethodonadaptee:
![Page 48: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/48.jpg)
//Adapterclassmethodprocessfunc(adapterAdapter)process(){fmt.Println("Adapterprocess")adapter.adaptee.convert()}//AdapteeStructtypeAdapteestruct{adapterTypeint}//Adapteeclassmethodconvertfunc(adapteeAdaptee)convert(){fmt.Println("Adapteeconvertmethod")}//mainmethodfuncmain(){varprocessorIProcess=Adapter{}processor.process()}
Runthefollowingcommands:gorunadapter.go
Thefollowingscreenshotdisplaystheoutput:
Let'stakealookatBridgepatterninthenextsection.
![Page 49: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/49.jpg)
BridgeBridgedecouplestheimplementationfromtheabstraction.Theabstractbaseclasscanbesubclassedtoprovidedifferentimplementationsandallowimplementationdetailstobemodifiedeasily.Theinterface,whichisabridge,helpsinmakingthefunctionalityofconcreteclassesindependentfromtheinterfaceimplementerclasses.Thebridgepatternsallowtheimplementationdetailstochangeatruntime.Thebridgepatterndemonstratestheprinciple,preferringcompositionoverinheritance.Ithelpsinsituationswhereoneshouldsubclassmultipletimesorthogonaltoeachother.Runtimebindingoftheapplication,mappingoforthogonalclasshierarchies,andplatformindependenceimplementationarethescenarioswherethebridgepatterncanbeapplied.Thebridgepatterncomponentsareabstraction,refinedabstraction,implementer,andconcreteimplementer.Abstractionistheinterfaceimplementedasanabstractclassthatclientsinvokewith themethodontheconcreteimplementer.Abstractionmaintainsahas-a relationshipwiththeimplementation,insteadofan is-a relationship.Thehas-a relationshipismaintainedbycomposition.Abstractionhasareferenceoftheimplementation.Refinedabstractionprovidesmorevariationsthanabstraction.Let'ssayIDrawShapeisaninterfacewiththe drawShape method. DrawShapeimplementstheIDrawShapeinterface.Wecreatean IContourbridgeinterface withthe drawContour method.Thecontourclassimplementsthe IContourinterface.Theellipseclasswillhavea,b,rpropertiesanddrawShape(aninstanceofDrawShape).Theellipseclassimplementsthe contour bridgeinterfacetoimplementthe drawContour method.The drawContour methodcallsthe drawShape methodonthe drawShape instance.Thefollowingcodedemonstratesthebridgeimplementation:
//mainpackagehasexamplesshown//inHands-OnDataStructuresandalgorithmswithGobookpackagemain//importingfmtpackageimport("fmt")//IDrawShapeinterfacetypeIDrawShapeinterface{drawShape(x[5]float32,y[5]float32)}//DrawShapestruct
![Page 50: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/50.jpg)
//DrawShapestruct
typeDrawShapestruct{}
![Page 51: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/51.jpg)
drawShapemethod
ThedrawShapemethoddrawstheshapegiventhecoordinates,asshowninthefollowingcode:
//DrawShapestructhasmethoddrawShapewithfloatxandycoordinatesfunc(drawShapeDrawShape)drawShape(x[5]float32,y[5]float32){fmt.Println("DrawingShape")}//IContourinteracetypeIContourinterface{drawContour(x[5]float32,y[5]float32)resizeByFactor(factorint)}//DrawContourstructtypeDrawContourstruct{x[5]float32y[5]float32shapeDrawShapefactorint}
![Page 52: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/52.jpg)
drawContourmethod
The drawContourmethod ofthe DrawContour classcallsthe drawShape methodontheshapeinstance,thisisshowninthefollowingcode:
//DrawContourmethoddrawContourgiventhecoordinatesfunc(contourDrawContour)drawContour(x[5]float32,y[5]float32){fmt.Println("DrawingContour")contour.shape.drawShape(contour.x,contour.y)}//DrawContourmethodresizeByFactorgivenfactorfunc(contourDrawContour)resizeByFactor(factorint){contour.factor=factor}//mainmethodfuncmain(){varx=[5]float32{1,2,3,4,5}vary=[5]float32{1,2,3,4,5}varcontourIContour=DrawContour{x,y,DrawShape{},2}contour.drawContour(x,y)contour.resizeByFactor(2)}
Runthefollowingcommands:gorunbridge.go
Thefollowingscreenshotdisplaystheoutput:
WewilltakealookatComposite,Decorator,FacadeandFlyweightdesignpatternsinthenextsections.
![Page 53: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/53.jpg)
CompositeAcompositeisagroupofsimilarobjectsinasingleobject.Objectsarestoredinatreeformtopersistthewholehierarchy.Thecompositepatternisusedtochangeahierarchicalcollectionofobjects.The compositepatternismodeledonaheterogeneouscollection.Newtypesofobjectscanbeaddedwithoutchangingtheinterfaceandtheclientcode.Youcanusethecompositepattern,forexample,forUIlayoutsontheweb,fordirectorytrees,andformanagingemployeesacrossdepartments.Thepatternprovidesamechanismtoaccesstheindividualobjectsandgroupsinasimilarmanner.Thecompositepatterncomprisesthecomponentinterface,componentclass,composite,andclient:
Thecomponentinterfacedefinesthedefaultbehaviorofallobjectsandbehaviorsforaccessingthecomponentsofthecomposite.Thecompositeandcomponentclassesimplementthecomponentinterface.Theclientinteractswiththecomponentinterfacetoinvokemethodsinthecomposite.
Let'ssaythereisan IComposite interfacewiththeperformmethodandBranchClass thatimplementsIComposite andhasthe addLeaf,addBranch,andperform methods.TheLeafletclassimplementsICompositewiththeperformmethod. BranchClasshasaone-to-manyrelationshipwithleafsandbranches.Iteratingoverthebranchrecursively,onecantraversethecompositetree,asshowninthefollowingcode:
//mainpackagehasexamplesshown//inHands-OnDataStructuresandalgorithmswithGobookpackagemain//importingfmtpackageimport("fmt")//ICompositeinterfacetypeICompositeinterface{perform()}//LeafletstructtypeLeafletstruct{namestring}//Leafletclassmethodperformfunc(leaf*Leaflet)perform(){fmt.Println("Leaflet"+leaf.name)}//BranchstructtypeBranchstruct{leafs[]Leaflet
![Page 54: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/54.jpg)
leafs[]Leaflet
namestringbranches[]Branch}
The performmethodofthe Branch class callsthe perform methodonbranchandleafs,asseeninthecode:
//Branchclassmethodperformfunc(branch*Branch)perform(){fmt.Println("Branch:"+branch.name)for_,leaf:=rangebranch.leafs{leaf.perform()}for_,branch:=rangebranch.branches{branch.perform()}}//Branchclassmethodaddleafletfunc(branch*Branch)add(leafLeaflet){branch.leafs=append(branch.leafs,leaf)}
Asshowninthefollowingcode,the addBranchmethod ofthe Branch class addsanewbranch:
//BranchclassmethodaddBranchbranchfunc(branch*Branch)addBranch(newBranchBranch){branch.branches=append(branch.branches,newBranch)}//BranchclassmethodgetLeafletsfunc(branch*Branch)getLeaflets()[]Leaflet{returnbranch.leafs}//mainmethodfuncmain(){varbranch=&Branch{name:"branch1"}varleaf1=Leaflet{name:"leaf1"}varleaf2=Leaflet{name:"leaf2"}varbranch2=Branch{name:"branch2"}branch.add(leaf1)branch.add(leaf2)branch.addBranch(branch2)branch.perform()}
Runthefollowingcommands:goruncomposite.go
Thefollowingscreenshotdisplaystheoutput:
![Page 55: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/55.jpg)
Let'stakealookatDecoratorpatterninthenextsection.
![Page 56: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/56.jpg)
DecoratorInascenariowhereclassresponsibilitiesareremovedoradded,thedecoratorpatternisapplied.Thedecoratorpatternhelpswithsubclassingwhen modifyingfunctionality,insteadofstaticinheritance.Anobjectcanhavemultipledecoratorsandrun-timedecorators.Thesingleresponsibilityprinciplecanbeachievedusingadecorator. The decoratorcanbeappliedto windowcomponentsandgraphicalobjectmodeling.Thedecoratorpatternhelpswithmodifyingexistinginstanceattributesandaddingnewmethodsatrun-time.Thedecoratorpatternparticipantsarethecomponentinterface,theconcretecomponentclass,andthe decoratorclass:
Theconcretecomponentimplementsthecomponentinterface.Thedecoratorclassimplementsthecomponentinterfaceandprovidesadditionalfunctionalityinthesamemethodoradditionalmethods.Thedecoratorbasecanbeaparticipantrepresentingthebaseclassforalldecorators.
Let'ssayIProcessisaninterfacewiththeprocessmethod.ProcessClassimplementsaninterfacewiththeprocessmethod.ProcessDecoratorimplementstheprocessinterfaceandhasaninstanceofProcessClass.ProcessDecoratorcanaddmorefunctionalitythan ProcessClass,asshowninthefollowingcode:
//mainpackagehasexamplesshown//inHands-OnDataStructuresandalgorithmswithGobookpackagemain//importingfmtpackageimport("fmt")//IProcessInterfacetypeIProcessinterface{process()}//ProcessClassstructtypeProcessClassstruct{}//ProcessClassmethodprocessfunc(process*ProcessClass)process(){fmt.Println("ProcessClassprocess")}//ProcessDecoratorstructtypeProcessDecoratorstruct{processInstance*ProcessClass}
Inthefollowingcode,theProcessDecoratorclassprocessmethod invokestheprocessmethodonthedecoratorinstanceofProcessClass:
![Page 57: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/57.jpg)
//ProcessDecoratorclassmethodprocessfunc(decorator*ProcessDecorator)process(){ifdecorator.processInstance==nil{fmt.Println("ProcessDecoratorprocess")}else{fmt.Printf("ProcessDecoratorprocessand")decorator.processInstance.process()}}//mainmethodfuncmain(){varprocess=&ProcessClass{}vardecorator=&ProcessDecorator{}decorator.process()decorator.processInstance=processdecorator.process()}
Runthefollowingcommands:gorundecorator.go
Thefollowingscreenshotdisplaystheoutput:
Let'stakealookatFacadepatterninthenextsection.
![Page 58: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/58.jpg)
FacadeFacadeisusedtoabstractsubsysteminterfaceswithahelper.Thefacadedesignpatternisusedinscenarioswhenthenumberofinterfacesincreasesandthesystemgetscomplicated.Facadeisanentrypointtodifferentsubsystems,anditsimplifiesthedependenciesbetweenthesystems.Thefacadepatternprovidesaninterfacethathidestheimplementationdetailsofthehiddencode.Alooselycoupledprinciplecanberealizedwithafacadepattern.YoucanuseafacadetoimprovepoorlydesignedAPIs.InSOA,aservicefacadecanbeusedtoincorporatechangestothecontractandimplementation.The facadepatternismadeupofthe facadeclass,moduleclasses,andaclient:
Thefacadedelegatestherequestsfromtheclienttothemoduleclasses.Thefacadeclasshidesthecomplexitiesofthesubsystemlogicandrules.Moduleclassesimplementthebehaviorsandfunctionalitiesofthemodulesubsystem.Theclientinvokesthefacademethod.Thefacadeclassfunctionalitycanbespreadacrossmultiplepackagesandassemblies.
Forexample,account,customer,andtransactionaretheclassesthathaveaccount,customer,andtransactioncreationmethods.BranchManagerFacadecanbeusedbytheclienttocreateanaccount,customer,andtransaction:
//mainpackagehasexamplesshown//inHands-OnDataStructuresandalgorithmswithGobookpackagemain//importingfmtpackageimport("fmt")//AccountstructtypeAccountstruct{idstringaccountTypestring}//Accountclassmethodcreate-createsaccountgivenAccountTypefunc(account*Account)create(accountTypestring)*Account{fmt.Println("accountcreationwithtype")account.accountType=accountTypereturnaccount}//AccountclassmethodgetByIdgivenidstringfunc(account*Account)getById(idstring)*Account{fmt.Println("gettingaccountbyId")returnaccount
![Page 59: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/59.jpg)
returnaccount
}
Theaccountclasshasthe deleteById method,whichisusedtodeleteanaccountwithagivenID,asshowninthefollowingcode:
//AccountclassmethoddeleteByIdgivenidstringfunc(account*Account)deleteById(idstring)(){fmt.Println("deleteaccountbyid")}//CustomerstructtypeCustomerstruct{namestringidint}
Inthefollowingcode,thecustomerclasshasamethodthatcreatesanewcustomerwithname:
//Customerclassmethodcreate-createCustomergivennamefunc(customer*Customer)create(namestring)*Customer{fmt.Println("creatingcustomer")customer.name=namereturncustomer}//TransactionstructtypeTransactionstruct{idstringamountfloat32srcAccountIdstringdestAccountIdstring}
Asshowninthefollowingcode,thetransactionclasshasthe create methodforcreatingatransaction:
//TransactionclassmethodcreateTransactionfunc(transaction*Transaction)create(srcAccountIdstring,destAccountIdstring,amountfloat32)*Transaction{fmt.Println("creatingtransaction")transaction.srcAccountId=srcAccountIdtransaction.destAccountId=destAccountIdtransaction.amount=amountreturntransaction}//BranchManagerFacadestructtypeBranchManagerFacadestruct{account*Accountcustomer*Customertransaction*Transaction}//methodNewBranchManagerFacadefuncNewBranchManagerFacade()*BranchManagerFacade{return&BranchManagerFacade{&Account{},&Customer{},&Transaction{}}}
![Page 60: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/60.jpg)
BranchManagerFacadehasthe createCustomerAccount method,whichcallsthe createmethodonthe customerclassinstance,asshowninthefollowingcode:
//BranchManagerFacadeclassmethodcreateCustomerAccountfunc(facade*BranchManagerFacade)createCustomerAccount(customerNamestring,accountTypestring)(*Customer,*Account){varcustomer=facade.customer.create(customerName)varaccount=facade.account.create(accountType)returncustomer,account}//BranchManagerFacadeclassmethodcreateTransactionfunc(facade*BranchManagerFacade)createTransaction(srcAccountIdstring,destAccountIdstring,amountfloat32)*Transaction{vartransaction=facade.transaction.create(srcAccountId,destAccountId,amount)returntransaction}
ThemainmethodcallstheNewBranchManagerFacademethodtocreateafacade.Themethodsonfacadeareinvokedtocreatecustomerandaccount:
//mainmethodfuncmain(){varfacade=NewBranchManagerFacade()varcustomer*Customervaraccount*Accountcustomer,account=facade.createCustomerAccount("ThomasSmith","Savings")fmt.Println(customer.name)fmt.Println(account.accountType)vartransaction=facade.createTransaction("21456","87345",1000)fmt.Println(transaction.amount)}
Runthefollowingcommands:gorunfacade.go
Thefollowingscreenshotdisplaystheoutput:
![Page 61: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/61.jpg)
Let'stakealookatFlyweightpatterninthenextsection.
![Page 62: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/62.jpg)
FlyweightFlyweightisusedtomanagethestateofanobjectwithhighvariation.Thepatternallowsustosharecommonpartsoftheobjectstateamongmultipleobjects,insteadofeachobjectstoringit.Variableobjectdataisreferredtoasextrinsicstate,andtherestoftheobjectstateisintrinsic.Extrinsicdataispassedtoflyweightmethodsandwillneverbestoredwithinit.Flyweightpatternhelpsreducetheoverallmemoryusageandtheobjectinitializingoverhead.Thepatternhelpscreateinterclassrelationshipsandlowermemorytoamanageablelevel.Flyweightobjectsareimmutable.Valueobjectsareagoodexampleoftheflyweightpattern.Flyweightobjectscanbecreatedinasinglethreadmode,ensuringoneinstancepervalue.Inaconcurrentthreadscenario,multipleinstancesarecreated.Thisisbasedontheequalitycriterionofflyweightobjects.TheparticipantsoftheflyweightpatternaretheFlyWeightinterface,ConcreteFlyWeight,FlyWeightFactory,andthe Clientclasses:
TheFlyWeightinterfacehasamethodthroughwhichflyweightscangetandactontheextrinsicstate.ConcreteFlyWeightimplementstheFlyWeightinterfacetorepresentflyweightobjects.FlyweightFactoryisusedtocreateandmanageflyweightobjects.TheclientinvokesFlyweightFactorytogetaflyweightobject.UnsharedFlyWeightcanhaveafunctionalitythatisnotshared.Clientclasses
Let'ssayDataTransferObjectisaninterfacewiththe getIdmethod.DataTransferObjectFactorycreatesadatatransferobjectthroughgetDataTransferObjectbytheDTOtype.TheDTOtypesarecustomer,employee,manager,andaddress,asshowninthefollowingcode:
//mainpackagehasexamplesshown//inHands-OnDataStructuresandalgorithmswithGobookpackagemain//importingfmtpackageimport("fmt")//DataTransferObjectFactorystructtypeDataTransferObjectFactorystruct{poolmap[string]DataTransferObject}//DataTransferObjectFactoryclassmethodgetDataTransferObjectfunc(factoryDataTransferObjectFactory)getDataTransferObject(dtoTypestring)DataTransferObject{vardto=factory.pool[dtoType]
![Page 63: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/63.jpg)
vardto=factory.pool[dtoType]
ifdto==nil{fmt.Println("newDTOofdtoType:"+dtoType)switchdtoType{case"customer":factory.pool[dtoType]=Customer{id:"1"}case"employee":factory.pool[dtoType]=Employee{id:"2"}case"manager":factory.pool[dtoType]=Manager{id:"3"}case"address":factory.pool[dtoType]=Address{id:"4"}}dto=factory.pool[dtoType]}
returndto}
Inthefollowingcode,theDataTransferObjectinterfaceisimplementedbytheCustomerclass:
//DataTransferObjectinterfacetypeDataTransferObjectinterface{getId()string}//CustomerstructtypeCustomerstruct{idstring//sequencegeneratornamestringssnstring}//CustomerclassmethodgetIdfunc(customerCustomer)getId()string{//fmt.Println("gettingcustomerId")returncustomer.id}//EmployeestructtypeEmployeestruct{idstringnamestring}//EmployeeclassmethodgetIdfunc(employeeEmployee)getId()string{returnemployee.id}//ManagerstructtypeManagerstruct{idstringnamestringdeptstring}
TheDataTransferObjectinterfaceisimplementedbythe Managerclass,asshowninthefollowingcode:
![Page 64: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/64.jpg)
//ManagerclassmethodgetIdfunc(managerManager)getId()string{returnmanager.id}//AddressstructtypeAddressstruct{idstringstreetLine1stringstreetLine2stringstatestringcitystring}//AddressclassmethodgetIdfunc(addressAddress)getId()string{returnaddress.id}//mainmethodfuncmain(){varfactory=DataTransferObjectFactory{make(map[string]DataTransferObject)}varcustomerDataTransferObject=factory.getDataTransferObject("customer")fmt.Println("Customer",customer.getId())varemployeeDataTransferObject=factory.getDataTransferObject("employee")fmt.Println("Employee",employee.getId())varmanagerDataTransferObject=factory.getDataTransferObject("manager")fmt.Println("Manager",manager.getId())varaddressDataTransferObject=factory.getDataTransferObject("address")fmt.Println("Address",address.getId())}
Runthefollowingcommands:gorunflyweight.go
Thefollowingscreenshotdisplaystheoutput:
![Page 65: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/65.jpg)
WewilltakealookatPrivateclassandProxydatapatternsinthenextsections.
![Page 66: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/66.jpg)
PrivateclassdataTheprivateclassdatapatternsecuresthedatawithinaclass.Thispatternencapsulatestheinitializationoftheclassdata.Thewriteprivilegesofpropertieswithintheprivateclassareprotected,andpropertiesaresetduringconstruction.Theprivateclasspatternprintstheexposureofinformationbysecuringitinaclassthatretainsthestate.Theencapsulationofclassdatainitializationisascenariowherethispatternisapplicable.Accountisaclasswithaccountdetailsandacustomername.AccountDetailsistheprivateattributeofAccount ,andCustomerNameisthepublicattribute.JSONmarshalingofAccounthas CustomerNameasapublicproperty.AccountDetailsisthepackagepropertyinGo(modeledasprivateclassdata):
//mainpackagehasexamplesshown//inHands-OnDataStructuresandalgorithmswithGobookpackagemain//importingfmtandencoding/jsonpackagesimport("encoding/json""fmt")//AccountDetailsstructtypeAccountDetailsstruct{idstringaccountTypestring}//AccountstructtypeAccountstruct{details*AccountDetailsCustomerNamestring}//AccountclassmethodsetDetailsfunc(account*Account)setDetails(idstring,accountTypestring){account.details=&AccountDetails{id,accountType}}
Asshowninthefollowingcode,theAccountclasshasthe getId method,whichreturnsthe id privateclassattribute:
//AccountclassmethodgetIdfunc(account*Account)getId()string{returnaccount.details.id}//AccountclassmethodgetAccountTypefunc(account*Account)getAccountType()string{returnaccount.details.accountType}
![Page 67: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/67.jpg)
Themainmethodcallsthe AccountinitializerwithCustomerName.Thedetailsoftheaccountaresetdetailswiththe setDetailsmethod:
//mainmethodfuncmain(){varaccount*Account=&Account{CustomerName:"JohnSmith"}account.setDetails("4532","current")jsonAccount,_:=json.Marshal(account)fmt.Println("PrivateClasshidden",string(jsonAccount))fmt.Println("AccountId",account.getId())fmt.Println("AccountType",account.getAccountType())}
Runthefollowingcommands:gorunprivateclass.go
Thefollowingscreenshotdisplaystheoutput:
Let'stakealookatProxypatterninthenextsection.
![Page 68: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/68.jpg)
ProxyTheproxypatternforwardstoarealobjectandactsasaninterfacetoothers.Theproxypatterncontrolsaccesstoanobjectandprovidesadditionalfunctionality.Theadditionalfunctionalitycanberelatedtoauthentication,authorization,andprovidingrightsofaccesstotheresource-sensitiveobject.Therealobjectneednotbemodifiedwhileprovidingadditionallogic.Remote,smart,virtual,andprotectionproxiesarethescenarioswherethispatternisapplied.Itisalsousedtoprovideanalternativetoextendfunctionalitywithinheritanceandobjectcomposition.Aproxyobjectisalsoreferredtoasasurrogate,handle,orwrapper.Theproxypatterncomprisesthe subjectinterface,the RealSubjectclass,andthe Proxyclass:
Subjectisaninterfaceforthe RealObjectandProxyclass.TheRealSubjectobjectiscreatedandmaintainedasareferenceinthe Proxyclass. RealSubjectisresourcesensitive,requiredtobeprotected,andexpensivetocreate. RealObjectisaclassthatimplementsthe IRealObjectinterface.IthasaperformActionmethod. VirtualProxyisusedtoaccessRealObjectandinvokethe performActionmethod.
Thefollowingcodeshowsanimplementationofproxypattern://mainpackagehasexamplesshown//inHands-OnDataStructuresandalgorithmswithGobookpackagemain//importingfmtpackageimport("fmt")//IRealObjectinterfacetypeIRealObjectinterface{performAction()}//RealObjectstructtypeRealObjectstruct{}RealObjectclassimplementsIRealObjectinterface.TheclasshasmethodperformAction.//RealObjectclassmethodperformActionfunc(realObject*RealObject)performAction(){fmt.Println("RealObjectperformAction()")}//VirtualProxystructtypeVirtualProxystruct{realObject*RealObject}
![Page 69: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/69.jpg)
}
//VirtualProxyclassmethodperformActionfunc(virtualProxy*VirtualProxy)performAction(){ifvirtualProxy.realObject==nil{virtualProxy.realObject=&RealObject{}}fmt.Println("VirtualProxyperformAction()")virtualProxy.realObject.performAction()}//mainmethodfuncmain(){varobjectVirtualProxy=VirtualProxy{}object.performAction()}
Runthefollowingcommands:gorunvirtualproxy.go
Thefollowingscreenshotdisplaystheoutput:
Nowthatweknowtheclassificationofdatastructuresandthedesignpatternsused,let'sgoaheadandtakealookattherepresentationofalgorithms.
![Page 70: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/70.jpg)
RepresentationofalgorithmsAflowchartandpseudocodearemethodsofrepresentingalgorithms.Analgorithmshowsthelogicofhowaproblemissolved.AflowcharthasdifferentrepresentationsymbolssuchasEntry,Exit,Task,Input/Output,DecisionPoint,andInterBlock.Astructuredprogramconsistsofaseriesofthesesymbolstoperformaspecifictask.Pseudocodehasdocumentation,action,andflowcontrolkeywordstovisualizeanalgorithm.ThedocumentationkeywordsareTASKandREM.SET,PUT,andGETaretheactionkeywords.Let'stakealookatthedifferentrepresentationsofalgorithms,thatis,flowchartsandPseudocodeinthenextsections.
![Page 71: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/71.jpg)
FlowchartTheflowcontrolkeywordsareSET,LOOP,(WHILE,UNTIL),REP,andPOST. Thefollowingflowchartshowsaformulaoranalgorithmtocalculatethedividendgivenanumberofshares,thefacevalue,andthedividendpercentage.ThestartandendaretheEntryandExitsymbols.Theinputnumberofshares,sharefacevalue,anddividendpercentageusetheInputsymbol.ThecomputedividendandoutputdividendusetheTasksymbolandOutputsymbolrespectively:
![Page 72: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/72.jpg)
Inthenextsection,we'll takealookatpseudocode,representationofalgorithms.
![Page 73: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/73.jpg)
PseudocodePseudocodeisahigh-leveldesignofaprogramoralgorithm.Sequenceandselectionaretwoconstructsusedinpseudocode.Pseudocodeiseasierthanaflowchartvisualizesthealgorithmwhilepseudocodecanbeeasilymodifiedandupdated.Errorsindesigncanbecaughtveryearlyinpseudocode.Thissavesthecostoffixingdefectslater.Togiveanexample,wewanttofindthemaxvalueinanarrayoflengthn.Thepseudocodewillbewrittenasfollows:
maximum(arr){
n<-len(arr)
max<-arr[0]
fork<-0,ndo{
Ifarr[k]>max{
max<-arr[k]
}
}
returnmax
}
Nowthatweknowthedifferentwaystorepresentthealgorithm,let'stakealookathowwecanmonitoritscomplexityandperformanceinthenextsection.
![Page 74: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/74.jpg)
ComplexityandperformanceanalysisTheefficiencyofanalgorithmismeasuredthroughvariousparameters,suchasCPUtime,memory,disk,andnetwork.Thecomplexityishowthealgorithmscaleswhenthenumberofinputparametersincreases.Performanceisameasureoftime,space,memory,andotherparameters.Algorithmsarecomparedbytheirprocessingtimeandresourceconsumption.ComplexitymeasurestheparametersandisrepresentedbytheBigOnotation.
![Page 75: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/75.jpg)
ComplexityanalysisofalgorithmsThecomplexityofanalgorithmismeasuredbythespeedofthealgorithm.Typically,thealgorithmwillperformdifferentlybasedonprocessorspeed,diskspeed,memory,andotherhardwareparameters.Hence,asymptoticalcomplexityisusedtomeasurethecomplexityofanalgorithm.Analgorithmisasetofstepstobeprocessedbydifferentoperationstoachieveatask.Thetimetakenforanalgorithmtocompleteisbasedonthenumberofstepstaken.Let'ssayanalgorithmiteratesthroughanarray, m,ofsize10andupdatetheelementstothesumofindexand200.Thecomputationaltimewillbe10*t,wheret isthetimetakentoadd twointegersandupdatethemtoanarray.Thenextstepwillbeprintingthemafteriteratingoveranarray.The t timeparameterwillvarywiththehardwareofthecomputerused.Asymptotically,thecomputationaltimegrowsasafactorof10,asshowninthefollowingcode:
//mainpackagehasexamplesshown//inHands-OnDataStructuresandalgorithmswithGobookpackagemain//importingfmtpackageimport("fmt")//mainmethodfuncmain(){varm[10]intvarkintfork=0;k<10;k++{m[k]=k+200fmt.Printf("Element[%d]=%d\n",k,m[k])}}
Runthefollowingcommands:goruncomplexity.go
Thefollowingscreenshotdisplaystheoutput:
![Page 76: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/76.jpg)
Let'stakealookatthedifferentcomplexitytypesinthenextsections.
![Page 77: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/77.jpg)
BigOnotation
The T(n)timefunctionrepresentsthealgorithmcomplexitybasedonBigOnotation.T(n)=O(n)statesthatanalgorithmhasalineartimecomplexity.UsingBigOnotation,theconstanttime,lineartime,logarithmictime,cubictime,andquadratictimecomplexityaredifferentcomplexitytypesforanalgorithm.Lineartime, O(n),isusedasameasureofcomplexityinscenariossuchaslinearsearch,traversing,andfindingtheminimumandmaximumnumberofarrayelements.ArrayListandqueuearedatastructuresthathavethesemethods.Analgorithmthathaslogarithmictime, O(logn),isabinarysearchinatreedatastructure.Bubblesort,selectionsort,andinsertionsortalgorithmshavecomplexityofquadratictime, O(n2).BigOmegaΩandbigThetaΘarenotationsforthelowerandupperboundsforaparticularalgorithm.Theworstcase,bestcase,averagecase,andamortizedrun-timecomplexityisusedforanalysisofalgorithms.Amortizedrun-timecomplexityisreferredtoas2n.Asymptotically,itwilltendtoO(1).BigOnotationisalsousedtodeterminehowmuchspaceisconsumedbythealgorithm.Thishelpsusfindthebestandworstcasescenarios,relativetospaceandtime.Let'stakealookatlinearcomplexityinthenextsection.
![Page 78: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/78.jpg)
LinearcomplexityAnalgorithmisoflinearcomplexityiftheprocessingtimeorstoragespaceisdirectlyproportionaltothenumberofinputelementstobeprocessed.InBigOnotation,linearcomplexityispresentedasO(n).StringmatchingalgorithmssuchastheBoyer-MooreandUkkonenhavelinearcomplexity.Linearcomplexity, O(n),isdemonstratedinanalgorithmasfollows:
//mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain//importingfmtpackageimport("fmt")//mainmethodfuncmain(){varm[10]intvarkintfork=0;k<10;k++{m[k]=k*200fmt.Printf("Element[%d]=%d\n",k,m[k])}}
Runthefollowingcommands:gorunlinear_complexity.go
Thefollowingscreenshotdisplaystheoutput:
![Page 79: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/79.jpg)
Let'stakealookatquadraticcomplexityinthenextsection.
![Page 80: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/80.jpg)
QuadraticcomplexityAnalgorithmisofquadraticcomplexityiftheprocessingtimeisproportionaltothesquareofthenumberofinputelements. Inthefollowingcase,thecomplexityofthealgorithmis10*10=100.Thetwoloopshaveamaximumof 10.ThequadraticcomplexityforamultiplicationtableofnelementsisO(n2).Quadraticcomplexity, O(n2),isshowninthefollowingexample:
//mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain//importingfmtpackageimport("fmt")//mainmethodfuncmain(){vark,lintfork=1;k<=10;k++{fmt.Println("MultiplicationTable",k)forl=1;l<=10;l++{varxint=l*kfmt.Println(x)}}}
Runthefollowingcommands:gorunquadratic_complexity.go
Thefollowingscreenshotdisplaystheoutput:
![Page 81: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/81.jpg)
Let'stakealookatcubiccomplexityinthenextsection.
![Page 82: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/82.jpg)
CubiccomplexityInthecaseofcubiccomplexity,theprocessingtimeofanalgorithmisproportionaltothecubeoftheinputelements. Thecomplexityofthefollowingalgorithmis10*10*10=1,000.Thethreeloopshaveamaximumof10.ThecubiccomplexityforamatrixupdateisO(n3).CubiccomplexityO(n3)isexplainedinthefollowingexample:
//mainpackagehasexamplesshown//inHands-OnDataStructuresandalgorithmswithGobookpackagemain//importingfmtpackageimport("fmt")//mainmethodfuncmain(){vark,l,mintvararr[10][10][10]intfork=0;k<10;k++{forl=0;l<10;l++{form=0;m<10;m++{arr[k][l][m]=1fmt.Println("Elementvalue",k,l,m,"is",arr[k][l][m])}}}}
Runthefollowingcommands:goruncubic_complexity.go
Thefollowingscreenshotdisplaystheoutput:
![Page 83: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/83.jpg)
Let'stakealookatlogarithmiccomplexityinthenextsection.
![Page 84: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/84.jpg)
LogarithmiccomplexityAnalgorithmisoflogarithmiccomplexityiftheprocessingtimeisproportionaltothelogarithmoftheinputelements.Thelogarithmbaseistypically2.ThefollowingtreeisabinarytreewithLeftNodeandRightNode.TheinsertoperationisofO(logn)complexity,wherenisthenumberofnodes.Logarithmiccomplexityispresentedasfollows:
//mainpackagehasexamplesshown//inHands-OnDataStructuresandalgorithmswithGobookpackagemain//importingfmtpackageimport("fmt")//TreestructtypeTreestruct{LeftNode*TreeValueintRightNode*Tree}
Asshowninthefollowingcode,theTreeclasshasthe insertmethod,whichinsertstheelementgivenmistheintegerelement:
//Treeinsertmethodforinsertingatmpositionfunc(tree*Tree)insert(mint){iftree!=nil{iftree.LeftNode==nil{tree.LeftNode=&Tree{nil,m,nil}}else{iftree.RightNode==nil{tree.RightNode=&Tree{nil,m,nil}}else{iftree.LeftNode!=nil{tree.LeftNode.insert(m)}else{tree.RightNode.insert(m)}}}}else{tree=&Tree{nil,m,nil}}}//printmethodforprintingaTreefuncprint(tree*Tree){iftree!=nil{fmt.Println("Value",tree.Value)fmt.Printf("TreeNodeLeft")
![Page 85: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/85.jpg)
fmt.Printf("TreeNodeLeft")
print(tree.LeftNode)fmt.Printf("TreeNodeRight")print(tree.RightNode)}else{fmt.Printf("Nil\n")}}
Themainmethodcallstheinsertmethodontreetoinsertthe 1, 3,5,and7 elements,asshowninthefollowingcode:
//mainmethodfuncmain(){vartree*Tree=&Tree{nil,1,nil}print(tree)tree.insert(3)print(tree)tree.insert(5)print(tree)tree.LeftNode.insert(7)print(tree)}
Runthefollowingcommands:goruntree.go
Thefollowingscreenshotdisplaystheoutput:
![Page 86: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/86.jpg)
Nowthatweknowaboutthecomplexitiesinalgorithmsandanalyzingtheirperformance,let'stakealookatbruteforcealgorithmsinthenextsection.
![Page 87: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/87.jpg)
BruteforcealgorithmsAbruteforcealgorithmsolvesaproblembasedonthestatementandtheproblemdefinition.Bruteforcealgorithmsforsearchandsortaresequentialsearchandselectionsort.Exhaustivesearchisanotherbruteforcealgorithmwherethesolutionisinasetofcandidatesolutionswithdefinitiveproperties.Thespaceinwhichthesearchhappensisastateandcombinatorialspace,whichconsistsofpermutations,combinations,orsubsets.BruteForcealgorithmsareknownforwideapplicabilityandsimplicityinsolvingcomplexproblems.Searching,stringmatching,andmatrixmultiplicationaresomescenarioswheretheyareused.Singlecomputationaltaskscanbesolvedusingbruteforcealgorithms.Theydonotprovideefficientalgorithms.Thealgorithmsareslowandnon-performant.Representationofabruteforcealgorithmisshowninthefollowingcode:
//mainpackagehasexamplesshown//inHands-OnDataStructuresandalgorithmswithGobookpackagemain//importingfmtpackageimport("fmt")//findElementmethodgivenarrayandkelementfuncfindElement(arr[10]int,kint)bool{variintfori=0;i<10;i++{ifarr[i]==k{returntrue}}returnfalse}//mainmethodfuncmain(){vararr=[10]int{1,4,7,8,3,9,2,4,1,8}varcheckbool=findElement(arr,10)fmt.Println(check)varcheck2bool=findElement(arr,9)fmt.Println(check2)}
Runthefollowingcommands:gorunbruteforce.go
Thefollowingscreenshotdisplaystheoutput:
![Page 88: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/88.jpg)
Afterbruteforcealgorithms,let'scoverdivideandconqueralgorithmsinthenextsection.
![Page 89: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/89.jpg)
DivideandconqueralgorithmsAdivideandconqueralgorithmbreaksacomplexproblemintosmallerproblemsandsolvesthesesmallerproblems.Thesmallerproblemwillbefurtherbrokendowntillitisaknownproblem.Theapproachistorecursivelysolvethesub-problemsandmergethesolutionsofthesub-problems.Recursion,quicksort,binarysearch,fastFouriertransform,andmergesortaregoodexamplesofdivideandconqueralgorithms.Memoryisefficientlyusedwiththesealgorithms.Performanceissometimesanissueinthecaseofrecursion.Onmultiprocessormachines,thesealgorithmscanbeexecutedondifferentprocessorsafterbreakingthemdownintosub-problems.Adivideandconqueralgorithmisshowninthefollowing code:
//mainpackagehasexamplesshown//inHands-OnDataStructuresandalgorithmswithGobookpackagemain//importingfmtpackageimport("fmt")
Asshowninthefollowingcode,theFibonaccimethodtakesthe k integerparameterandreturnstheFibonaccinumberfork.ThemethodusesrecursiontocalculatetheFibonaccinumbers.Therecursionalgorithmisappliedbydividingtheproblemintothe k-1integerandthe k-2 integer:
//fibonaccimethodgivenkintegerfuncfibonacci(kint)int{ifk<=1{return1}returnfibonacci(k-1)+fibonacci(k-2)}//mainmethodfuncmain(){varmint=5form=0;m<8;m++{varfib=fibonacci(m)fmt.Println(fib)}}
Runthefollowingcommands:gorundivide.go
![Page 90: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/90.jpg)
Thefollowingscreenshotdisplaystheoutput:
Let'stakealookatwhatbacktrackingalgorithmsareinthenextsection.
![Page 91: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/91.jpg)
BacktrackingalgorithmsAbacktrackingalgorithmsolvesaproblembyconstructingthesolutionincrementally.Multipleoptionsareevaluated,andthealgorithmchoosestogotothenextcomponentofthesolutionthroughrecursion.Backtrackingcanbeachronologicaltypeorcantraversethepaths,dependingontheproblemthatyouaresolving.Backtrackingisanalgorithmthatfindscandidatesolutionsandrejectsacandidateonthebasisofitsfeasibilityandvalidity.Backtrackingisusefulinscenariossuchasfindingavalueinanunorderedtable.Itisfasterthanabruteforcealgorithm,whichrejectsalargenumberofsolutionsinaniteration.Constraintsatisfactionproblemssuchasparsing,rulesengine,knapsackproblems,andcombinatorialoptimizationaresolvedusingbacktracking.Thefollowingisanexampleofabacktrackingalgorithm.Theproblemistoidentifythecombinationsofelementsinanarrayof10elementswhosesumisequalto18.ThefindElementsWithSum methodrecursivelytriestofindthecombination.Wheneverthesumgoesbeyondthektarget,itbacktracks:
//mainpackagehasexamplesshown//inHands-OnDataStructuresandalgorithmswithGobookpackagemain//importingfmtpackageimport("fmt")//findElementsWithSumofkfromarrofsizefuncfindElementsWithSum(arr[10]int,combinations[19]int,sizeint,kint,addValueint,lint,mint)int{varnumint=0ifaddValue>k{return-1}ifaddValue==k{num=num+1varpint=0forp=0;p<m;p++{fmt.Printf("%d,",arr[combinations[p]])}fmt.Println("")}variintfori=l;i<size;i++{//fmt.Println("m",m)combinations[m]=lfindElementsWithSum(arr,combinations,size,k,addValue+arr[i],l,m+1)l=l+1
![Page 92: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/92.jpg)
l=l+1
}returnnum}//mainmethodfuncmain(){vararr=[10]int{1,4,7,8,3,9,2,4,1,8}varaddedSumint=18varcombinations[19]intfindElementsWithSum(arr,combinations,10,addedSum,0,0,0)//fmt.Println(check)//varcheck2bool=findElement(arr,9)//fmt.Println(check2)}
Runthefollowingcommands:gorunbacktracking.go
Thefollowingscreenshotdisplaystheoutput:
![Page 93: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/93.jpg)
![Page 94: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/94.jpg)
SummaryThischaptercoveredthedefinitionofabstractdatatypes,classifyingdatastructuresintolinear,nonlinear,homogeneous,heterogeneous,anddynamictypes.Abstractdatatypessuchascontainer,list,set,map,graph,stack,andqueuewerepresentedinthischapter.Thechaptercoveredtheperformanceanalysisofdatastructuresandstructuraldesignpatterns.Welookedattheclassificationofdatastructuresandstructuraldesignpatterns.Youcanusealgorithmssuchasbruteforce,divideandconquer,andbacktrackingbycalculatingthecomplexityandperformanceanalysis.Thechoiceofalgorithmandtheuseofdesignpatternsanddatastructuresarethekeytakeaways. Inthenextchapter,wewilldiscussdatastructuresinGo.Thefollowingdatastructureswillbecovered:
ArraysSlicesTwo-dimensionalslices Maps
![Page 95: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/95.jpg)
Questionsandexercises1. Giveanexamplewhereyoucanuseacompositepattern.2. Foranarrayof10elementswitharandomsetofintegers,identifythemaximumandminimum.Calculatethecomplexityofthealgorithm.
3. Tomanagethestateofanobject,whichstructuralpatternisrelevant?4. Awindowissub-classedtoaddascrollbartomakeitascrollablewindow.Whichpatternisappliedinthisscenario?
5. Findthecomplexityofabinarytreesearchalgorithm.6. Identifythesubmatricesof2x2ina3x3matrix.Whatisthecomplexityofthealgorithmthatyouhaveused?
7. Explainwithascenariothedifferencebetweenbruteforceandbacktrackingalgorithms.1. Arulesengineusesbacktrackingtoidentifytherulesaffectedbythechange.Showanexamplewherebacktrackingidentifiestheaffectedrules.
2. Drawaflowchartforthealgorithmofthecalculationofprofit-lossgiventhecostprice,sellingprice,andquantity.
3. Writethepseudocodeforanalgorithmthatcomparesthestringsandidentifiesthesubstringwithinastring.
![Page 96: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/96.jpg)
Furtherreading
ThefollowingbooksarerecommendedifyouwanttofindoutmoreaboutGangofFourdesignpatterns,algorithms,anddatastructures:
DesignPatterns, byErichGamma,RichardHelm,RalphJohnson,andJohnVlissidesIntroductiontoAlgorithms –ThirdEdition,byThomasH.Cormen,CharlesE.Leiserson,RonaldL.Rivest,andCliffordSteinDatastructuresandAlgorithms:AnEasyIntroduction,by RudolphRussell
![Page 97: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/97.jpg)
GettingStartedwithGoforDataStructuresandAlgorithmsTheGoprogramminglanguagehasbeenrapidlyadoptedbydevelopersforbuildingwebapplications.Withitsimpressiveperformanceandeaseofdevelopment,Goenjoysthesupportofawidevarietyofopensourceframeworksforbuildingscalableandhighlyperformantwebservicesandapps.ThemigrationtoGolanghastakenplacemainlybecauseofitsfast,lightweight,andinbuiltconcurrencyfeatures.Thisbringswithittheneedtolearndatastructuresandalgorithmswiththisgrowinglanguage.Indatastructures,acollectionofelementsofasingletypeiscalledanarray.Slicesaresimilartoarraysexceptthattheyhaveunusualproperties.Sliceoperationssuchasenlargingasliceusingappendandcopymethods,assigningpartsofaslice,appendingaslice,andappendingapartofaslicearepresentedwithcodesamples. DatabaseoperationsandCRUDwebformsarethescenariosinwhichGodatastructuresandalgorithmsaredemonstrated.Inthischapter,wewilldiscussthefollowingGolanguage-specificdatastructures:
ArraysSlicesTwo-dimensionalslicesMapsDatabaseoperationsVariadicfunctionsCRUDwebforms
![Page 98: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/98.jpg)
TechnicalrequirementsInstallGoVersion1.10at https://golang.org/doc/install,dependingonyouroperatingsystem. ThecodefilesforthischaptercanbefoundatthefollowingGitHubURL: https://github.com/PacktPublishing/Learn-Data-Structures-and-Algorithms-with-Golang/tree/master/Chapter02.Inthischapter,databaseoperationsrequirethe github.com/go-sql-driver/mysql package.Inadditiontothis,MySQL(4.1+)needstobeinstalledfromhttps://dev.mysql.com/downloads/mysql/.Runthefollowingcommand:
goget-ugithub.com/go-sql-driver/mysql
![Page 99: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/99.jpg)
ArraysArraysarethemostfamousdatastructuresindifferentprogramminglanguages.Differentdatatypescanbehandledaselementsinarrayssuchasint,float32,double,andothers.Thefollowingcodesnippetshowstheinitializationofanarray(arrays.go):
vararr=[5]int{1,2,4,5,6}
Anarray'ssizecanbefoundwiththelen()function.Aforloopisusedforaccessingalltheelementsinanarray,asfollows:
variint
fori=0;i<len(arr);i++{
fmt.Println("printingelements",arr[i]
}
Inthefollowingcodesnippet,therangekeywordisexplainedindetail.Therangekeywordcanbeusedtoaccesstheindexandvalueforeachelement:
varvalueint
fori,value=rangearr{
fmt.Println("range",value)
}
The_blankidentifierisusediftheindexisignored.Thefollowing code showshowa _blankidentifiercanbeused:
for_,value=rangearr{
fmt.Println("blankrange",value)
}
![Page 100: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/100.jpg)
Runthefollowingcommand:gorunarrays.go
Thefollowingscreenshotdisplaystheoutput:
Goarraysarenotdynamicbuthaveafixedsize.Toaddmoreelementsthanthesize,abiggerarrayneedstobecreatedandalltheelementsoftheoldoneneedtobecopied.Anarrayispassedasavaluethroughfunctionsbycopyingthearray.Passingabigarraytoafunctionmightbe
![Page 101: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/101.jpg)
functionsbycopyingthearray.Passingabigarraytoafunctionmightbeaperformanceissue.Nowthatwehavecoveredwhatarraysare,let'stakealookatslicesinthenextsection.
![Page 102: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/102.jpg)
SlicesGoSliceisanabstractionoverGoArray. MultipledataelementsofthesametypeareallowedbyGoarrays.ThedefinitionofvariablesthatcanholdseveraldataelementsofthesametypeareallowedbyGoArray,butitdoesnothaveanyprovisionofinbuiltmethodstoincreaseitssizeinGo.ThisshortcomingistakencareofbySlices. AGoslicecanbeappendedtoelementsafterthecapacityhasreacheditssize. Slicesaredynamicandcandoublethe currentcapacity inordertoaddmoreelements.Let'stakealookatthelenfunctioninthenextsection.
![Page 103: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/103.jpg)
Thelenfunction Thelen()functiongivesthecurrentlengthofslice,andthecapacityofslicecanbeobtainedusingthecap()function. Thefollowingcodesampleshowsthebasicslicecreationandappendingaslice(basic_slice.go):
varslice=[]int{1,3,5,6}
slice=append(slice,8)
fmt.Println(“Capacity”,cap(slice))
fmt.Println(“Length”,len(slice))
Runthefollowingcommandtoexecutetheprecedingcode:gorunbasic_slice.go
Thefollowingscreenshotdisplaystheoutput:
Let'stakealookattheslicefunctioninthenextsection.
![Page 104: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/104.jpg)
Slicefunction
Slicesarepassedbyreferringtofunctions.Bigslicescanbepassedtofunctionswithoutimpactingperformance.Passingasliceasareferencetoafunctionisdemonstratedinthecodeasfollows(slices.go):
//twiceValuemethodgivensliceofinttype
functwiceValue(slice[]int){
variint
varvalueint
fori,value=rangeslice{
slice[i]=2*value
}
}
//mainmethod
funcmain(){
varslice=[]int{1,3,5,6}
twiceValue(slice)
variint
![Page 105: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/105.jpg)
fori=0;i<len(slice);i++{
fmt.Println(“newslicevalue”,slice[i])
}
}
Runthefollowingcommand:gorunslices.go
Thefollowingscreenshotdisplaystheoutput:
Nowthatweknowwhatslicesare,let'smoveontotwo-dimensionalslicesinthenextsection.
![Page 106: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/106.jpg)
Two-dimensionalslicesTwo-dimensionalslicesaredescriptorsofatwo-dimensionalarray.Atwo-dimensionalslice isacontiguoussectionofanarraythatisstoredawayfromthesliceitself.Itholdsreferencestoanunderlyingarray.Atwo-dimensionalslicewillbeanarrayofarrays,whilethecapacityofaslicecanbeincreasedbycreatinganewsliceandcopyingthecontentsoftheinitialsliceintothenewone.Thisisalsoreferredtoasasliceofslices.Thefollowingisanexampleofatwo-dimensionalarray.A2Darrayiscreatedandthearrayelementsareinitializedwithvalues.twodarray.goisthecodeexhibitthat'spresentedinthefollowingcode:
//mainpackagehasexamplesshown
//inGoDataStructuresandalgorithmsbook
packagemain
//importingfmtpackage
import(
"fmt"
)
//mainmethod
funcmain(){
varTwoDArray[8][8]int
TwoDArray[3][6]=18
TwoDArray[7][4]=3
![Page 107: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/107.jpg)
TwoDArray[7][4]=3
fmt.Println(TwoDArray)
}
Runthefollowingcommand:goruntwodarray.go
Thefollowingscreenshotdisplaystheoutput:
Fordynamicallocation,weusesliceofslices.Inthefollowingcode,sliceofslicesisexplainedastwo-dimensionalslices—twodslices.go:
//inGoDataStructuresandalgorithmsbook
packagemain
//importingfmtpackage
import(
"fmt"
)
![Page 108: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/108.jpg)
//mainmethod
funcmain(){
varrowsint
varcolsint
rows=7
cols=9
vartwodslices=make([][]int,rows)
variint
fori=rangetwodslices{
twodslices[i]=make([]int,cols)
}
fmt.Println(twodslices)
}
Runthefollowingcommands:
![Page 109: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/109.jpg)
goruntwodslices.go
Thefollowingscreenshotdisplaystheoutput:
Theappend methodonthesliceisusedtoappendnewelementstotheslice.Iftheslicecapacityhasreachedthesizeoftheunderlyingarray,thenappendincreasesthesizebycreatinganewunderlyingarrayandaddingthenewelement. slic1isasubsliceofarrstartingfromzeroto3(excluded),whileslic2isasubsliceofarrstartingfrom1(inclusive)to5(excluded).Inthefollowingsnippet,theappendmethodcallsonslic2 toaddanew12element(append_slice.go):
vararr=[]int{5,6,7,8,9}
varslic1=arr[:3]
fmt.Println("slice1",slic1)
varslic2=arr[1:5]
fmt.Println("slice2",slic2)
varslic3=append(slic2,12)
fmt.Println("slice3",slic3)
Runthefollowingcommands:gorunappend_slice.go
![Page 110: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/110.jpg)
Thefollowingscreenshotdisplaystheoutput:
Nowthatwehavecoveredwhattwo-dimensionalslicesare,let'stakealookatmapsinthenextsection.
![Page 111: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/111.jpg)
MapsMapsareusedtokeeptrackof keysthataretypes,suchasintegers,strings,float,double,pointers,interfaces,structs,andarrays.Thevaluescanbeofdifferenttypes.Inthefollowingexample,thelanguageofthemaptypewithakeyintegerandavaluestringiscreated(maps.go):
varlanguages=map[int]string{
3:“English”,
4:“French”,
5:“Spanish”
}
Mapscanbecreatedusingthemake method,specifyingthekeytypeandthevaluetype.Productsofa maptypewithakeyintegerandvaluestringareshowninthefollowingcodesnippet:
varproducts=make(map[int]string)
products[1]=“chair”
products[2]=“table”
Aforloopisusedforiteratingthroughthemap.Thelanguagesmapisiteratedasfollows:
variint
varvaluestring
fori,value=rangelanguages{
![Page 112: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/112.jpg)
fmt.Println("language",i,“:",value)
}
fmt.Println("productwithkey2",products[2])
Retrievingvalueanddeleting slice operationsusingtheproductsmap isshowninthefollowingcode:
fmt.Println(products[2])
delete(products,”chair”)
fmt.Println("products",products)
Runthefollowingcommands:gorunmaps.go
Thefollowingscreenshotdisplaystheoutput:
Nowthatwe'vecoveredmaps,let'smoveontodatabaseoperations.
![Page 113: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/113.jpg)
DatabaseoperationsInthissection,wewilltakealookatsomeofdatabaseoperationsusingappropriateexamples. Let'sstartwiththeGetCustomermethodinthenextsection.
![Page 114: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/114.jpg)
TheGetCustomermethod
TheGetCustomermethodretrievestheCustomerdatafromthedatabase.Tostartwith,thecreate databaseoperationisshowninthefollowingexample.Customeristhetablewiththe Customerid,CustomerName,andSSNattributes.The GetConnectionmethodreturnsthedatabaseconnection,whichisusedtoquerythedatabase.Thequerythenreturnstherowsfromthedatabasetable.Inthefollowingcode,databaseoperationsareexplainedindetail(database_operations.go):
//mainpackagehasexamplesshown//inHands-OnDataStructuresandalgorithmswithGobookpackagemain
//importingfmt,database/sql,net/http,text/templatepackageimport("fmt""database/sql"_"github.com/go-sql-driver/mysql")
//CustomerClasstypeCustomerstruct{CustomerIdintCustomerNamestringSSNstring}//GetConnectionmethodwhichreturnssql.DBfuncGetConnection()(database*sql.DB){databaseDriver:="mysql"databaseUser:="newuser"databasePass:="newuser"databaseName:="crm"database,error:=sql.Open(databaseDriver,databaseUser+":"+databasePass+"@/"+databaseName)iferror!=nil{panic(error.Error())}returndatabase}//GetCustomersmethodreturnsCustomerArrayfuncGetCustomers()[]Customer{vardatabase*sql.DBdatabase=GetConnection()
varerrorerrorvarrows*sql.Rowsrows,error=database.Query("SELECT*FROMCustomerORDERBYCustomeridDESC")iferror!=nil{
![Page 115: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/115.jpg)
iferror!=nil{
panic(error.Error())}varcustomerCustomercustomer=Customer{}
varcustomers[]Customercustomers=[]Customer{}forrows.Next(){varcustomerIdintvarcustomerNamestringvarssnstringerror=rows.Scan(&customerId,&customerName,&ssn)iferror!=nil{panic(error.Error())}customer.CustomerId=customerIdcustomer.CustomerName=customerNamecustomer.SSN=ssncustomers=append(customers,customer)}
deferdatabase.Close()
returncustomers}
//mainmethodfuncmain(){
varcustomers[]Customercustomers=GetCustomers()fmt.Println("Customers",customers)
}
Runthefollowingcommands:gorundatabase_operations.go
Thefollowingscreenshotdisplaystheoutput:
![Page 116: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/116.jpg)
Let'stakealookattheInsertCustomermethodinthenextsection.
![Page 117: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/117.jpg)
TheInsertCustomermethod
TheINSERToperationisasfollows.TheInsertCustomermethodtakestheCustomerparameter andcreatesapreparedstatementfortheINSERTstatement.Thestatementisusedtoexecutetheinsertionofcustomerrowsintothetable,asshowninthefollowingsnippet:
//InsertCustomermethodwithparametercustomerfuncInsertCustomer(customerCustomer){vardatabase*sql.DBdatabase=GetConnection()
varerrorerrorvarinsert*sql.Stmtinsert,error=database.Prepare("INSERTINTOCUSTOMER(CustomerName,SSN)VALUES(?,?)")iferror!=nil{panic(error.Error())}insert.Exec(customer.CustomerName,customer.SSN)
deferdatabase.Close()
}
Let'stakealookatthevariadicfunctionsinthenextsection.
![Page 118: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/118.jpg)
VariadicfunctionsAfunctioninwhichwepassaninfinitenumberofarguments,insteadofpassingthemoneatatime,iscalledavariadicfunction. Thetypeofthefinalparameterisprecededbyanellipsis(...),whiledeclaringavariadicfunction;thisshowsusthatthefunctionmightbecalledwithanynumberofargumentsofthistype.Variadicfunctionscanbeinvokedwithavariablenumberofparameters.fmt.Printlnisacommonvariadicfunction,asfollows:
//mainmethodfuncmain(){
varcustomers[]Customer
customers=GetCustomers()
fmt.Println("BeforeInsert",customers)
varcustomerCustomer
customer.CustomerName="ArnieSmith"
customer.SSN="2386343"
InsertCustomer(customer)
customers=GetCustomers()
fmt.Println("AfterInsert",customers)}
![Page 119: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/119.jpg)
Runthefollowingcommands:gorundatabase_operations.go
Thefollowingscreenshotdisplaystheoutput:
Let'sstarttheupdateoperationinthenextsection.
![Page 120: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/120.jpg)
Theupdateoperation
Theupdate operationisasfollows.The UpdateCustomermethodtakestheCustomerparameter andcreatesapreparedstatementfortheUPDATEstatement.Thestatementisusedtoupdateacustomerrowinthetable:
//UpdateCustomermethodwithparametercustomerfuncUpdateCustomer(customerCustomer){
vardatabase*sql.DB
database=GetConnection()
varerrorerror
varupdate*sql.Stmt
update,error=database.Prepare("UPDATECUSTOMERSETCustomerName=?,SSN=?WHERECustomerId=?")
iferror!=nil{
panic(error.Error())
}update.Exec(customer.CustomerName,customer.SSN,customer.CustomerId)
deferdatabase.Close()
}//mainmethod
funcmain(){
![Page 121: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/121.jpg)
funcmain(){
varcustomers[]Customer
customers=GetCustomers()
fmt.Println("BeforeUpdate",customers)
varcustomerCustomer
customer.CustomerName="GeorgeThompson"
customer.SSN="23233432"
customer.CustomerId=5
UpdateCustomer(customer)
customers=GetCustomers()
fmt.Println("AfterUpdate",customers)}
Runthefollowingcommands:gorundatabase_operations.go
Thefollowingscreenshotdisplaystheoutput:
![Page 122: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/122.jpg)
Let'stakealookatthedeleteoperationinthenextsection.
![Page 123: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/123.jpg)
Thedeleteoperation
Thedeleteoperationisasfollows.TheDeleteCustomermethodtakestheCustomerparameterandcreatesapreparedstatementfortheDELETEstatement.Thestatementisusedtoexecutethedeletionofacustomerrowinthetable:
//DeleteCustomermethodwithparametercustomerfuncdeleteCustomer(customerCustomer){
vardatabase*sql.DB
database=GetConnection()
varerrorerror
vardelete*sql.Stmt
delete,error=database.Prepare("DELETEFROMCustomerWHERECustomerid=?")
iferror!=nil{
panic(error.Error())
}
delete.Exec(customer.CustomerId)
deferdatabase.Close()
![Page 124: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/124.jpg)
}//mainmethod
funcmain(){
varcustomers[]Customer
customers=GetCustomers()
fmt.Println("BeforeDelete",customers)
varcustomerCustomer
customer.CustomerName="GeorgeThompson"
customer.SSN="23233432"
customer.CustomerId=5
deleteCustomer(customer)
customers=GetCustomers()
fmt.Println("AfterDelete",customers)
}
Runthefollowingcommands:
![Page 125: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/125.jpg)
gorundatabase_operations.go
Thefollowingscreenshotdisplaystheoutput:
Nowthatwearedonewithvariadicfunctions,let'sgoaheadandlookatCRUDwebformsinthenextsection.
![Page 126: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/126.jpg)
CRUDwebformsInthissection,wewillexplainwebforms usingbasicexamples,showingyouhowtoperformvariousactions.TostartabasicHTMLpagewiththeGonet/httppackage,thewebformsexampleisasfollows(webforms.go).Thishasawelcomegreetinginmain.html:
//mainpackagehasexamplesshown
//inHands-OnDataStructuresandalgorithmswithGobook
packagemain
//importingfmt,database/sql,net/http,text/templatepackage
import(
"net/http"
"text/template"
"log")
//Homemethodrendersthemain.html
funcHome(writerhttp.ResponseWriter,reader*http.Request){
vartemplate_html*template.Template
template_html=template.Must(template.ParseFiles("main.html"))
template_html.Execute(writer,nil)
![Page 127: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/127.jpg)
template_html.Execute(writer,nil)
}
//mainmethod
funcmain(){
log.Println("Serverstartedon:http://localhost:8000")
http.HandleFunc("/",Home)
http.ListenAndServe(":8000",nil)
}
Thecodeformain.htmlisasfollows:<html>
<body>
<p>WelcometoWebForms</p>
</body>
</html>
Runthefollowingcommands:gorunwebforms.go
Thefollowingscreenshotdisplaystheoutput:
![Page 128: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/128.jpg)
Thewebbrowseroutputisshowninthefollowingscreenshot:
TheCRMapplicationisbuiltwithwebformsasanexampletodemonstrateCRUDoperations.Wecanusethedatabaseoperationswebuiltintheprevioussection.Inthefollowingcode,the crmdatabaseoperationsarepresented.ThecrmdatabaseoperationsconsistofCRUDmethodssuchasCREATE,READ,UPDATE,andDELETEcustomeroperations.The GetConnectionmethodretrievesthedatabaseconnectionforperformingthedatabaseoperations(crm_database_operations.go):
//mainpackagehasexamplesshown
//inHands-OnDataStructuresandalgorithmswithGobook
packagemain
//importingfmt,database/sql,net/http,text/templatepackage
import(
![Page 129: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/129.jpg)
"database/sql"
_"github.com/go-sql-driver/mysql"
)//CustomerClass
typeCustomerstruct{
CustomerIdint
CustomerNamestring
SSNstring
}//GetConnectionmethodwhichreturnssql.DB
funcGetConnection()(database*sql.DB){
databaseDriver:="mysql"
databaseUser:="newuser"
databasePass:="newuser"
databaseName:=“crm"
database,error:=sql.Open(databaseDriver,
![Page 130: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/130.jpg)
database,error:=sql.Open(databaseDriver,
databaseUser+”:"+databasePass+"@/"+databaseName)
iferror!=nil{
panic(error.Error())
}
returndatabase
}
Asshowninthefollowingcode,theGetCustomerByIdmethodtakesthe customerIdparametertolookupinthecustomerdatabase.TheGetCustomerByIdmethodreturnsthecustomerobject:
//GetCustomerByIdwithparametercustomerIdreturnsCustomer
funcGetCustomerById(customerIdint)Customer{
vardatabase*sql.DB
database=GetConnection()
varerrorerror
varrows*sql.Rows
![Page 131: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/131.jpg)
rows,error=database.Query("SELECT*FROMCustomerWHERECustomerId=?",customerId)
iferror!=nil{
panic(error.Error())
}
varcustomerCustomer
customer=Customer{}
forrows.Next(){
varcustomerIdint
varcustomerNamestring
varSSNstring
error=rows.Scan(&customerId,&customerName,&SSN)
iferror!=nil{
panic(error.Error())
![Page 132: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/132.jpg)
}
customer.CustomerId=customerId
customer.CustomerName=customerName
customer.SSN=SSN
}
NowthatwehavecoveredCRUDwebforms,let'smoveontodeferandpanicinthenextsection.
![Page 133: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/133.jpg)
ThedeferandpanicstatementsThedeferstatementdefersthe executionofthefunctionuntilthesurroundingfunctionreturns.Thepanicfunctionstopsthecurrentflowandcontrol.Deferredfunctionsareexecutednormallyafterthepaniccall. Inthefollowingcodeexample,thedefercallgetsexecutedevenwhenthepaniccallisinvoked:
deferdatabase.Close()
returncustomer
}//GetCustomersmethodreturnsCustomerArray
funcGetCustomers()[]Customer{
vardatabase*sql.DB
database=GetConnection()
varerrorerror
varrows*sql.Rows
rows,error=database.Query("SELECT*FROMCustomerORDERBYCustomeridDESC")
iferror!=nil{
panic(error.Error())
![Page 134: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/134.jpg)
}
varcustomerCustomer
customer=Customer{}
varcustomers[]Customer
customers=[]Customer{}
forrows.Next(){
varcustomerIdint
varcustomerNamestring
varssnstring
error=rows.Scan(&customerId,&customerName,&ssn)
iferror!=nil{
panic(error.Error())
}
![Page 135: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/135.jpg)
customer.CustomerId=customerId
customer.CustomerName=customerName
customer.SSN=ssn
customers=append(customers,customer)
}
deferdatabase.Close()
returncustomers
}
Let'stakealookattheInsertCustomer,UpdateCustomer,andDeleteCustomermethodsinthefollowingsections.
![Page 136: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/136.jpg)
TheInsertCustomermethod
Inthefollowingcode,the InsertCustomermethodtakescustomerasaparametertoexecutetheSQLstatementforinsertingintotheCUSTOMERtable:
//InsertCustomermethodwithparametercustomerfuncInsertCustomer(customerCustomer){vardatabase*sql.DBdatabase=GetConnection()varerrorerrorvarinsert*sql.Stmtinsert,error=database.Prepare("INSERTINTOCUSTOMER(CustomerName,SSN)VALUES(?,?)")iferror!=nil{panic(error.Error())}insert.Exec(customer.CustomerName,customer.SSN)deferdatabase.Close()}
![Page 137: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/137.jpg)
TheUpdateCustomermethod
TheUpdateCustomermethodpreparestheUPDATEstatementbypassingtheCustomerNameandSSNfromthe customerobject;thisisshowninthefollowingcode:
//UpdateCustomermethodwithparametercustomerfuncUpdateCustomer(customerCustomer){vardatabase*sql.DBdatabase=GetConnection()varerrorerrorvarupdate*sql.Stmtupdate,error=database.Prepare("UPDATECUSTOMERSETCustomerName=?,SSN=?WHERECustomerId=?")iferror!=nil{panic(error.Error())}update.Exec(customer.CustomerName,customer.SSN,customer.CustomerId)deferdatabase.Close()}
![Page 138: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/138.jpg)
TheDeleteCustomermethod
TheDeleteCustomermethoddeletesthecustomerthat's passedbyexecutingtheDELETEstatement:
//DeleteCustomermethodwithparametercustomerfuncDeleteCustomer(customerCustomer){vardatabase*sql.DBdatabase=GetConnection()varerrorerrorvardelete*sql.Stmtdelete,error=database.Prepare("DELETEFROMCustomerWHERECustomerid=?")iferror!=nil{panic(error.Error())}delete.Exec(customer.CustomerId)deferdatabase.Close()}
Let'stakealookattheCRMwebapplicationinthenextsection.
![Page 139: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/139.jpg)
CRMwebapplication
TheCRMwebapplicationisshownasfollows,withvariouswebpathshandled.TheCRMapplicationcodeisshowninthefollowingcode.The HomefunctionexecutestheHometemplatewiththewriterparameter andthecustomersarray(crm_app.go):
//mainpackagehasexamplesshown//inHands-OnDataStructuresandalgorithmswithGobookpackagemain
//importingfmt,database/sql,net/http,text/templatepackageimport("fmt""net/http""text/template""log")
vartemplate_html=template.Must(template.ParseGlob("templates/*"))
//Home-executeTemplatefuncHome(writerhttp.ResponseWriter,request*http.Request){varcustomers[]Customercustomers=GetCustomers()log.Println(customers)template_html.ExecuteTemplate(writer,"Home",customers)
}
Let'stakealookattheCreate,Insert,Alter,Update,and Deletefunctions,aswellasthemainmethodinthefollowingsections.
![Page 140: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/140.jpg)
TheCreatefunction
Asshowninthefollowingcode,theCreatefunctiontakesthe writerandrequestparameterstorenderthe Create template:
//Create-executeTemplatefuncCreate(writerhttp.ResponseWriter,request*http.Request){
template_html.ExecuteTemplate(writer,"Create",nil)}
![Page 141: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/141.jpg)
TheInsertfunction
TheInsertfunctioninvokestheGetCustomersmethodtogetanarrayofcustomersandrenders the Hometemplatewiththe writerandcustomersarraysasparametersbyinvokingthe ExecuteTemplatemethod.Thisisshowninthefollowingcode:
//Insert-executetemplatefuncInsert(writerhttp.ResponseWriter,request*http.Request){
varcustomerCustomercustomer.CustomerName=request.FormValue("customername")customer.SSN=request.FormValue("ssn")InsertCustomer(customer)varcustomers[]Customercustomers=GetCustomers()template_html.ExecuteTemplate(writer,"Home",customers)
}
![Page 142: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/142.jpg)
TheAlterfunction
ThefollowingcodeshowshowtheAlterfunctionrenderstheHometemplatebyinvokingthe ExecuteTemplatemethodwiththe writerandcustomersarraysasparameters:
//Alter-executetemplatefuncAlter(writerhttp.ResponseWriter,request*http.Request){
varcustomerCustomervarcustomerIdintvarcustomerIdStrstringcustomerIdStr=request.FormValue("id")fmt.Sscanf(customerIdStr,"%d",&customerId)customer.CustomerId=customerIdcustomer.CustomerName=request.FormValue("customername")customer.SSN=request.FormValue("ssn")UpdateCustomer(customer)varcustomers[]Customercustomers=GetCustomers()template_html.ExecuteTemplate(writer,"Home",customers)
}
![Page 143: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/143.jpg)
TheUpdatefunction
TheUpdatefunctioninvokestheExecuteTemplatemethodwithwriterandcustomerlookedupbyid.TheExecuteTemplatemethodrendersthe UPDATE template:
//Update-executetemplatefuncUpdate(writerhttp.ResponseWriter,request*http.Request){
varcustomerIdintvarcustomerIdStrstringcustomerIdStr=request.FormValue("id")fmt.Sscanf(customerIdStr,"%d",&customerId)varcustomerCustomercustomer=GetCustomerById(customerId)
template_html.ExecuteTemplate(writer,"Update",customer)
}
![Page 144: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/144.jpg)
TheDeletefunction
TheDeletemethodrenderstheHometemplateafterdeletingthecustomerthat'sfoundbythe GetCustomerByIdmethod.TheViewmethodrenderstheViewtemplateafterfindingthecustomerbyinvokingthe GetCustomerByIdmethod:
//Delete-executeTemplatefuncDelete(writerhttp.ResponseWriter,request*http.Request){varcustomerIdintvarcustomerIdStrstringcustomerIdStr=request.FormValue("id")fmt.Sscanf(customerIdStr,"%d",&customerId)varcustomerCustomercustomer=GetCustomerById(customerId)DeleteCustomer(customer)varcustomers[]Customercustomers=GetCustomers()template_html.ExecuteTemplate(writer,"Home",customers)
}//View-executeTemplatefuncView(writerhttp.ResponseWriter,request*http.Request){varcustomerIdintvarcustomerIdStrstringcustomerIdStr=request.FormValue("id")fmt.Sscanf(customerIdStr,"%d",&customerId)varcustomerCustomercustomer=GetCustomerById(customerId)fmt.Println(customer)varcustomers[]Customercustomers=[]Customer{customer}customers.append(customer)template_html.ExecuteTemplate(writer,"View",customers)
}
![Page 145: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/145.jpg)
Themainmethod
Themainmethodhandlesthe Home,Alter,Create, Update,View,Insert,andDeletefunctionswithdifferentaliasesforlookupandrendersthetemplatesappropriately.HttpServerlistenstoport8000andwaitsfortemplatealiasinvocation:
//mainmethodfuncmain(){log.Println("Serverstartedon:http://localhost:8000")http.HandleFunc("/",Home)http.HandleFunc("/alter",Alter)http.HandleFunc("/create",Create)http.HandleFunc("/update",Update)http.HandleFunc("/view",View)http.HandleFunc("/insert",Insert)http.HandleFunc("/delete",Delete)http.ListenAndServe(":8000",nil)}
Let'stakealookattheHeader,Footer,Menu,Create,Update,andViewtemplatesinthefollowingsections.
![Page 146: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/146.jpg)
TheHeadertemplateTheHeadertemplatehastheHTMLheadandbody definedinthecodesnippet,asfollows.TheTITLE tagofthewebpageissettoCRMandthewebpagehasCustomerManagement–CRMascontent(Header.tmpl):
{{define"Header"}}
<!DOCTYPEhtml>
<html>
<head>
<title>CRM</title>
<metacharset="UTF-8"/>
</head>
<body>
<h1>CustomerManagement–CRM</h1>
{{end}}
![Page 147: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/147.jpg)
TheFootertemplateTheFootertemplatehastheHTMLandBODYclosetagsdefined.The Footertemplateispresentedinthefollowingcodesnippet(Footer.tmpl):
{{define"Footer"}}
</body>
</html>
{{end}}
![Page 148: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/148.jpg)
TheMenutemplateTheMenutemplatehasthelinksdefinedforHomeandCreateCustomer,asshowninthefollowingcode(Menu.tmpl):
{{define"Menu"}}
<ahref="/">Home</a>|<ahref="/create">CreateCustomer</a>
{{end}}
![Page 149: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/149.jpg)
TheCreatetemplateTheCreatetemplateconsistsofHeader,Menu,andFootertemplates.Theformtocreatecustomerfieldsisfoundinthecreatetemplate.Thisformissubmittedtoawebpath—/insert,asshowninthefollowingcodesnippet(Create.tmpl):
{{define"Create"}}
{{template"Header"}}
{{template"Menu"}}
<br>
<h1>CreateCustomer</h1>
<br>
<br>
<formmethod="post"action="/insert">
CustomerName:<inputtype="text"name="customername"placeholder="customername"autofocus/>
<br>
<br>
SSN:<inputtype="text"name="ssn"placeholder="ssn"/>
![Page 150: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/150.jpg)
SSN:<inputtype="text"name="ssn"placeholder="ssn"/>
<br>
<br>
<inputtype="submit"value="CreateCustomer"/>
</form>
{{template"Footer"}}
{{end}}
![Page 151: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/151.jpg)
TheUpdatetemplateTheUpdatetemplateconsistsofthe Header,Menu,andFootertemplates,asfollows.TheformtoupdatecustomerfieldsisfoundintheUpdatetemplate.Thisformissubmittedtoawebpath, /alter (Update.tmpl):
{{define"Update"}}{{template"Header"}}{{template"Menu"}}<br><h1>UpdateCustomer</h1><br><br><formmethod="post"action="/alter"><inputtype="hidden"name="id"value="{{.CustomerId}}"/>CustomerName:<inputtype="text"name="customername"placeholder="customername"value="{{.CustomerName}}"autofocus><br><br>SSN:<inputtype="text"name="ssn"value="{{.SSN}}"placeholder="ssn"/><br><br><inputtype="submit"value="UpdateCustomer"/></form>{{template"Footer"}}{{end}}
![Page 152: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/152.jpg)
TheViewtemplateTheViewtemplateconsistsofHeader,Menu,andFootertemplates.TheformtoviewthecustomerfieldsisfoundintheViewtemplate,whichispresentedincode asfollows(View.tmpl):
{{define"View"}}
{{template"Header"}}
{{template"Menu"}}
<br>
<h1>ViewCustomer</h1>
<br>
<br>
<tableborder="1">
<tr>
<td>CustomerId</td>
<td>CustomerName</td>
<td>SSN</td>
<td>Update</td>
<td>Delete</td>
![Page 153: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/153.jpg)
<td>Delete</td>
</tr>
{{if.}}
{{range.}}
<tr>
<td>{{.CustomerId}}</td>
<td>{{.CustomerName}}</td>
<td>{{.SSN}}</td>
<td><ahref="/delete?id={{.CustomerId}}"onclick="returnconfirm('Areyousureyouwanttodelete?');">Delete</a></td>
<td><ahref="/update?id={{.CustomerId}}">Update</a></td>
</tr>
{{end}}
{{end}}
</table>
{{template"Footer"}}
{{end}}
Runthefollowingcommands:
![Page 154: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/154.jpg)
goruncrm_app.gocrm_database_operations.go
Thefollowingscreenshotdisplaystheoutput:
Thewebbrowseroutputisshowninthefollowingscreenshot:
![Page 155: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/155.jpg)
![Page 156: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/156.jpg)
SummaryThischapterintroduceddatabaseoperationsandwebforms.Now,youwillbeabletobuildwebapplicationsthatcanstoredataindatabases.Arrays,slices,two-dimensionalslices,andmapswerecoveredwithcodesamples.Arraymethodssuchaslen,iteratingthroughanarrayusingfor,andrangewereexplainedinthischapterusingcodesnippets.Two-dimensionalarraysandsliceofsliceswerediscussedintheSlicessection.Mapswereexplainedwithvariousscenariossuchasaddingkeysandvalues,aswellasretrievinganddeletingvalues.Mapsofdifferenttypes,suchasstringsandintegers,werealsodiscussedinthischapter.Furthermore,variadicfunctions,deferredfunctioncalls,andpanicandrecoveroperationsweredemonstratedintheDatabaseoperationsandCRUDwebforms sections.TheCRMapplicationwasbuiltasawebapplicationwithdatapersistedintheMySQLdatabase. Databaseoperationsforadding,deleting,updating,andretrievingdatawereshownincodesnippets.Inaddition,webformsforcreating,updating,deleting,andviewingcustomerdatawerepresentedusingwebformswithtemplates.MySQLdriveranditsinstallationdetailswereprovidedintheTechnicalrequirementssectionofthischapter.Howtocreatea webapplicationusingGowasdemonstratedwithexecutiondetails.Thenextchapterwillhavetopicsrelatedto lineardatastructuressuchaslists,sets,tuples,andstacks.
![Page 157: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/157.jpg)
Questions1. Whatisthenameofthemethodtogetthesizeofanarray?2. Howdoyoufindthecapacityoftheslice?3. Howdoyouinitializethe2Dsliceofastringtype?4. Howdoyouaddanelementtotheslice?5. Usingcode,canyoudemonstratehowtocreateamapofkeystringsandvaluestrings?Initializethemapwithkeysandvaluesinthecode,iteratetheminaloop,andprintthekeysandvaluesinthecode.1. Howdoyoudeleteavalueinamap?2. Whatparametersarerequiredforgettingadatabaseconnection?3. Whichsql.Rowsclassmethodmakesitpossibletoreadtheattributesoftheentityinatable?
4. Whatdoesdeferdowhenadatabaseconnectionisclosed?5. Whichmethodallowsthesql.DBclasstocreateapreparedstatement?
![Page 158: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/158.jpg)
Furtherreading
Toreadmoreaboutarrays,mapsandslices,thefollowinglinksarerecommended:
LearningGoDataStructuresandAlgorithms[Video],by GustavoChaínMasteringGo,by MihalisTsoukalos
![Page 159: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/159.jpg)
Section2:BasicDataStructuresandAlgorithmsusingGo
Wewilltalkaboutdatastructures,includinglinear,non-linear,homogeneous,heterogeneous,anddynamictypes,aswellas classicalgorithms.Thissectioncoversdifferenttypesoflists,trees,arrays,sets,dictionaries,tuples,heaps,queues,andstacks,alongwithsorting,recursion,searching,andhashingalgorithms.Thissectioncontainsthefollowingchapters:
Chapter3, LinearDataStructuresChapter4, Non-LinearDataStructuresChapter5, HomogeneousDataStructuresChapter6, HeterogeneousDataStructuresChapter7, DynamicDataStructuresChapter8, ClassicAlgorithms
![Page 160: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/160.jpg)
LinearDataStructuresVariousapplications,suchasFacebook,Twitter,andGoogle,uselistsandlineardatastructures.Aswehavediscussedpreviously,datastructuresallowustoorganizevastswathesofdatainasequentialandorganizedmanner,therebyreducingtimeandeffortinworkingwithsuchdata.Lists,stacks,sets,andtuplesaresomeofthecommonlyusedlineardatastructures.Inthischapter, wewilldiscussthesedatastructuresbygivingexamplesofvariousproceduresinvolvingthem.Wewilldiscussthevariousoperationsrelatedtothesedatastructures,suchasinsertion,deletion,updating,traversing(oflists),reversing,andmergingwithvariouscodesamples. Wewillcoverthefollowinglineardatastructuresinthischapter:
ListsSetsTuplesStacks
![Page 161: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/161.jpg)
TechnicalrequirementsInstallGoversion1.10athttps://golang.org/doc/install,dependingonyouroperatingsystem.ThecodefilesforthischaptercanbefoundatthefollowingGitHubURL: https://github.com/PacktPublishing/Learn-Data-Structures-and-Algorithms-with-Golang/tree/master/Chapter03.
![Page 162: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/162.jpg)
ListsAlistisacollectionoforderedelements thatareusedtostorelistofitems. Unlikearraylists,thesecanexpandandshrinkdynamically.Listsalsobeusedasabaseforotherdatastructures,suchasstackandqueue.Listscanbeusedtostorelistsofusers,carparts,ingredients,to-doitems,andvariousothersuchelements.Listsarethemostcommonlyusedlineardatastructures. Thesewereintroducedinthelispprogramminglanguage.Inthischapter,linkedlistanddoublylinkedlistarethelistswewillcoverintheGolanguage.Let'sdiscusstheoperationsrelatedtoadd,update,remove,andlookuponlinkedlistanddoublylinkedlistinthefollowingsection.
![Page 163: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/163.jpg)
LinkedListLinkedListisasequenceofnodesthathavepropertiesandareferencetothenextnodeinthesequence.Itisalineardatastructurethatisusedtostoredata.Thedatastructurepermitstheadditionanddeletionofcomponentsfromanynodenexttoanothernode.Theyarenot storedcontiguouslyinmemory,whichmakesthemdifferentarrays.Thefollowingsectionswilllookatthestructuresandmethodsinalinkedlist.
![Page 164: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/164.jpg)
TheNodeclassTheNodeclasshasanintegertypedvariablewiththenameproperty.TheclasshasanothervariablewiththenamenextNode,whichisanodepointer.Linkedlistwillhaveasetofnodeswithintegerproperties, asfollows:
//NodeclasstypeNodestruct{propertyintnextNode*Node}
![Page 165: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/165.jpg)
TheLinkedListclassTheLinkedListclasshastheheadNodepointerasitsproperty.Bytraversingto nextNodefromheadNode,youcaniteratethroughthelinkedlist,asshowninthefollowingcode:
//LinkedListclasstypeLinkedListstruct{headNode*Node}
ThedifferentmethodsoftheLinkedListclass,suchasAddtoHead,IterateList,LastNode,AddtoEnd,NodeWithValue,AddAfter,andthemainmethod,arediscussedinthefollowingsections.
![Page 166: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/166.jpg)
TheAddToHeadmethod
TheAddToHeadmethodaddsthenodetothestartofthelinkedlist.TheAddToHeadmethod ofthe LinkedListclasshasaparameterintegerproperty.Thepropertyisusedtoinitializethenode.Anewnodeisinstantiatedanditspropertyissettothe property parameterthat'spassed. ThenextNodepointstothecurrentheadNodeoflinkedList,and headNodeissettothepointerofthenewnodethat'screated,asshowninthefollowingcode:
//AddToHeadmethodofLinkedListclassfunc(linkedList*LinkedList)AddToHead(propertyint){varnode=Node{}node.property=propertyifnode.nextNode!=nil{node.nextNode=linkedList.headNode}linkedList.headNode=&node}
Whenthenodewiththe 1 propertyisaddedtothehead,addingthe1 propertytotheheadoflinkedListsets headNodetocurrentNodewithavalueof 1,asyoucanseeinthefollowingscreenshot:
Let'sexecutethiscommandusingthemainmethod.Here, wehavecreatedaninstanceofaLinkedList classandaddedthe 1 and 3 integerpropertiestotheheadofthisinstance.Thelinkedlist'sheadNodepropertyisprintedafteraddingtheelements,asfollows:
//mainmethodfuncmain(){varlinkedListLinkedListlinkedList=LinkedList{}linkedList.AddToHead(1)linkedList.AddToHead(3)fmt.Println(linkedList.headNode.property)}
Runthefollowingcommandstoexecutethe linked_list.gofile:gorunlinked_list.go
Afterexecutingtheprecedingcommand,wegetthefollowingoutput:
![Page 167: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/167.jpg)
Let'stakealookattheIterateListmethodinthenextsection.
![Page 168: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/168.jpg)
TheIterateListmethod
TheIterateListmethodoftheLinkedListclassiteratesfromtheheadNode propertyandprintsthepropertyofthecurrentheadnode.Theiterationhappenswiththeheadnodemovesto nextNodeoftheheadNode propertyuntilthecurrentnodeisnolongerequaltonil.ThefollowingcodeshowstheIterateListmethodofthe LinkedListclass:
//IterateListmethoditeratesoverLinkedListfunc(linkedList*LinkedList)IterateList(){varnode*Nodefornode=linkedList.headNode;node!=nil;node=node.nextNode{fmt.Println(node.property)}}
![Page 169: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/169.jpg)
TheLastNodemethod
TheLastNodemethodofLinkedListreturnsthenodeattheendofthelist.Thelististraversedtocheckwhether nextNodeisnilfrom nextNode of headNode,asfollows:
//LastNodemethodreturnsthelastNode
func(linkedList*LinkedList)LastNode()*Node{varnode*NodevarlastNode*Nodefornode=linkedList.headNode;node!=nil;node=node.nextNode{ifnode.nextNode==nil{lastNode=node}}returnlastNode}
![Page 170: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/170.jpg)
TheAddToEndmethod
TheAddToEndmethodaddsthenodeattheendofthelist.Inthefollowingcode,thecurrent lastNodeisfoundanditsnextNode propertyissetastheaddednode:
//AddToEndmethodaddsthenodewithpropertytotheend
func(linkedList*LinkedList)AddToEnd(propertyint){varnode=&Node{}node.property=propertynode.nextNode=nilvarlastNode*NodelastNode=linkedList.LastNode()iflastNode!=nil{lastNode.nextNode=node}}
Inthefollowingscreenshot,the AddToEnd methodisinvokedwhenthenodewithapropertyvalue of 5isaddedtotheend.Addingthepropertythroughthismethodcreatesanodewithavalueof 5.Thelastnodeofthelisthasapropertyvalueof 5.ThenextNode propertyof lastNodeisnil.ThenextNodeof lastNodeissettothenodewithavalueof 5:
Let'stakealookattheNodeWithValuemethodinthenextsection.
![Page 171: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/171.jpg)
TheNodeWithValuemethod
Inthefollowingcodesnippet,the NodeWithValuemethodofLinkedListreturnsthenodewiththeproperty value. Thelististraversedandcheckedtoseewhetherthepropertyvalueisequaltotheparameterproperty:
//NodeWithValuemethodreturnsNodegivenparameterproperty
func(linkedList*LinkedList)NodeWithValue(propertyint)*Node{varnode*NodevarnodeWith*Nodefornode=linkedList.headNode;node!=nil;node=node.nextNode{ifnode.property==property{nodeWith=nodebreak;}}returnnodeWith}
![Page 172: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/172.jpg)
TheAddAftermethod
TheAddAftermethodaddsthenodeafteraspecificnode.TheAddAftermethodofLinkedListhas nodePropertyandpropertyparameters.Anodewiththe nodeProperty valueisretrievedusingthe NodeWithValuemethod.Anodewithpropertyiscreatedandaddedafterthe NodeWithnode,asfollows:
//AddAftermethodaddsanodewithnodePropertyafternodewithproperty
func(linkedList*LinkedList)AddAfter(nodePropertyint,propertyint){varnode=&Node{}node.property=propertynode.nextNode=nilvarnodeWith*NodenodeWith=linkedList.NodeWithValue(nodeProperty)ifnodeWith!=nil{node.nextNode=nodeWith.nextNodenodeWith.nextNode=node}}
Youthengetthefollowingoutputwhenthe AddAfter methodisinvokedwhenthenodewitha propertyvalueof 7isaddedafterthenodewithavalueof 1. ThenextNode propertyofthenodewithapropertyvalue of 1isnil.ThenextNode propertyofthenodewithapropertyvalue of 1 issettothenodewithavalueof 5:
Let'stakealookatthemainmethodinthenextsection.
![Page 173: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/173.jpg)
Themainmethod
Themainmethodaddsthenodeswithintegerpropertiesof 1,3,and5,asshowninthefollowingcode.Anodewithanintegerpropertyof 7 isaddedafterthenodewithanintegerpropertyof 1.The IterateListmethodisinvokedonthe linkedListinstance,asfollows:
//mainmethodfuncmain(){varlinkedListLinkedListlinkedList=LinkedList{}linkedList.AddToHead(1)linkedList.AddToHead(3)linkedList.AddToEnd(5)linkedList.AddAfter(1,7)linkedList.IterateList()}
Themainmethodadds1and3 totheheadofthelinkedlist.5isaddedtotheend.7isaddedafter1.Thelinkedlistwillbe3, 1,7,and 5.Runthefollowingcommandstoexecutethe linked_list.gofile:
gorunlinked_list.go
Afterexecutingtheprecedingcommand,wegetthefollowingoutput:
Let'stakealookatdoublylinkedlistinthenextsection.
![Page 174: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/174.jpg)
DoublylinkedlistInadoublylinkedlist,allnodeshaveapointertothenodetheyareconnectedto,oneithersideofthem,inthelist.Thismeansthateachnodeisconnectedtotwonodes,andwecantraverseforwardthroughtothenextnodeorbackwardthroughtothepreviousnode.Doublylinkedlistsallowinsertion,deletionand,obviously,traversingoperations.Thenodeclassdefinitionispresentedinthefollowingcodeexample:
//NodeclasstypeNodestruct{propertyintnextNode*NodepreviousNode*Node}
Thefollowingsectionsexplaindoublylinkedlistmethods,suchasthe NodeBetweenValues,AddToHead,AddAfter,AddToEnd,andmainmethods.
![Page 175: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/175.jpg)
TheNodeBetweenValuesmethod
TheNodeBetweenValuesmethodofthe LinkedListclassreturnsthenodethathasapropertylyingbetweenthe firstPropertyandsecondPropertyvalues.ThemethodtraversesthelisttofindoutwhetherthefirstPropertyandsecondPropertyintegerproperties matchonconsecutivenodes,asfollows:
//NodeBetweenValuesmethodofLinkedListfunc(linkedList*LinkedList)NodeBetweenValues(firstPropertyint,secondPropertyint)*Node{varnode*NodevarnodeWith*Nodefornode=linkedList.headNode;node!=nil;node=node.nextNode{ifnode.previousNode!=nil&&node.nextNode!=nil{ifnode.previousNode.property==firstProperty&&node.nextNode.property==secondProperty{nodeWith=nodebreak;}}}returnnodeWith}
Theexampleoutputafterthenodebetweenthevaluesmethodwasinvokedwith1and5 isshowninthefollowingscreenshot. ThenextNodeofthelastNodeissettothenodewithavalueof 5.Thenodewithapropertyvalueof 7isbetweenthenodeswithpropertyvaluesof 1and5:
Let'stakealookattheAddToHeadmethodinthenextsection.
![Page 176: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/176.jpg)
TheAddToHeadmethod
TheAddToHeadmethodofthedoublyLinkedListclasssetsthepreviousNode propertyofthecurrentheadNode ofthelinkedlisttothenodethat'saddedwithproperty.Thenodewithpropertywillbesetasthe headNodeoftheLinkedList methodinthefollowingcode:
//AddToHeadmethodofLinkedListfunc(linkedList*LinkedList)AddToHead(propertyint){varnode=&Node{}node.property=propertynode.nextNode=niliflinkedList.headNode!=nil{node.nextNode=linkedList.headNodelinkedList.headNode.previousNode=node}linkedList.headNode=node}
Theexampleoutputafterthe AddToHead methodwasinvokedwithproperty3 isasfollows.Anodewithproperty3iscreated.TheheadNode propertyofthelisthasapropertyvalueof 1.Thecurrentnodewithproperty3hasanextNode propertyof nil.ThenextNode propertyofthecurrentnodeissettoheadNodewithapropertyvalueof 1.ThepreviousnodeoftheheadNode propertyissettothecurrentnode:
Let'stakealookattheAddAftermethodinthenextsection.
![Page 177: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/177.jpg)
AddAftermethod
TheAddAftermethodaddsanodeafteraspecificnodetoadoublelinkedlist.The AddAftermethodofthedoubleLinkedListclasssearchesthenodewhosevalueisequaltonodeProperty.ThefoundnodeissetasthepreviousNodeofthenodethatwasaddedwithproperty.ThenextNodeoftheaddednodewillbethe nodeWithproperty'snextNode.ThepreviousNodeoftheaddednodewillbethenodethatwasfoundwithvalueequalto nodeProperty.ThenodeWith nodewillbeupdatedtothecurrentnode. Inthefollowingcode,theAddAftermethodisshown:
//AddAftermethodofLinkedListfunc(linkedList*LinkedList)AddAfter(nodePropertyint,propertyint){varnode=&Node{}node.property=propertynode.nextNode=nilvarnodeWith*NodenodeWith=linkedList.NodeWithValue(nodeProperty)ifnodeWith!=nil{
node.nextNode=nodeWith.nextNodenode.previousNode=nodeWithnodeWith.nextNode=node}}
Theexampleoutputafterthe AddAfter methodisinvokedwithproperty7isasfollows.Anodewithpropertyvalue7iscreated.ThenextNode propertyofthecreatednodeisnil.ThenextNode propertyofthecreatednodeissettoheadNodewithpropertyvalue1.ThepreviousNode propertyof headNodeissettothecurrentnode:
Let'stakealookattheAddToEndmethodinthenextsection.
![Page 178: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/178.jpg)
TheAddToEndmethod
TheAddToEndmethodaddsthenodetotheendofthedoublelinkedlist.TheAddToEndmethodofthe LinkedListclasscreatesanodewhosepropertyissetastheintegerparameterproperty.ThemethodsetsthepreviousNode propertyofthenodethatwasaddedwiththecurrentlastNode propertyasfollows.ThenextNodeofthecurrentlastNode propertyissettoanodeaddedwithpropertyattheendasfollows:
//AddToEndmethodofLinkedListfunc(linkedList*LinkedList)AddToEnd(propertyint){varnode=&Node{}node.property=propertynode.nextNode=nilvarlastNode*NodelastNode=linkedList.LastNode()iflastNode!=nil{
lastNode.nextNode=nodenode.previousNode=lastNode}}
Theexampleoutputafterthe AddToEnd methodwasinvokedwithproperty5isasfollows.Anodewithpropertyvalue5iscreated.ThelastNodeofthelisthaspropertyvalue1.ThenextNode propertyofthelastNodeisnil.ThenextNodeofthelastNodeissettothenodewithpropertyvalue5.ThepreviousNodeofthecreatednodeissettothenodewithpropertyvalue1:
Let'stakealookatthemainmethodinthenextsection.
![Page 179: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/179.jpg)
Themainmethod
Inthefollowingcodesnippet,themainmethodcallstheNodeBetweenValues propertywithfirstPropertyandsecondProperty.Thenodepropertybetweenvalues1and5isprinted:
//mainmethodfuncmain(){varlinkedListLinkedListlinkedList=LinkedList{}linkedList.AddToHead(1)linkedList.AddToHead(3)linkedList.AddToEnd(5)linkedList.AddAfter(1,7)fmt.Println(linkedList.headNode.property)varnode*Nodenode=linkedList.NodeBetweenValues(1,5)fmt.Println(node.property)}
Themainmethodcreatesalinkedlist.Thenodesareaddedtotheheadandend.Thenodebetweenvalues1and5issearchedanditspropertyisprinted.Runthefollowingcommand toexecutethedoubly_linked_list.gofile:
gorundoubly_linked_list.go
Afterexecutingtheprecedingcommand,wegetthefollowingoutput:
Thenextsectiontalksaboutsets,whicharelineardatastructures.
![Page 180: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/180.jpg)
SetsASetisalineardatastructurethathasacollectionofvaluesthatarenotrepeated.Asetcanstoreuniquevalueswithoutanyparticularorder.Intherealworld,setscanbeusedtocollectalltagsforblogpostsandconversationparticipantsinachat. ThedatacanbeofBoolean,integer,float,characters,andothertypes.Staticsetsallowonlyqueryoperations,whichmeansoperationsrelatedtoqueryingtheelements.Dynamicandmutablesetsallowfortheinsertionanddeletionofelements.Algebraicoperationssuchasunion,intersection,difference,andsubsetcanbedefinedonthesets.Thefollowingexampleshowsthe Set integerwithamap integerkeyandboolasavalue:
//mainpackagehasexamplesshown//inHands-OnDataStructuresandalgorithmswithGobookpackagemain//importingfmtpackageimport("fmt")//SetclasstypeSetstruct{integerMapmap[int]bool}//createthemapofintegerandboolfunc(set*Set)New(){set.integerMap=make(map[int]bool)}
TheAddElement,DeleteElement,ContainsElement,Intersect,Union,andmainmethodsarediscussedinthefollowingsections.
![Page 181: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/181.jpg)
TheAddElementmethod
TheAddElementmethodaddstheelementtoaset.Inthefollowingcodesnippet,theAddElementmethodoftheSet classaddstheelementto integerMapiftheelementisnotintheSet.TheintegerMap elementhasthekeyintegerandvalueasbool,asshowninthefollowingcode:
//addstheelementtothesetfunc(set*Set)AddElement(elementint){if!set.ContainsElement(element){set.integerMap[element]=true}}
TheexampleoutputafterinvokingtheAddElementmethodwithparameter2isasfollows. Thecheckisdoneifthereisanelementwithvalue2.Ifthereisnoelement,themapissettotruewiththekeyas2:
Let'stakealookattheDeleteElementmethodinthenextsection.
![Page 182: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/182.jpg)
TheDeleteElementmethod
TheDeleteElementmethoddeletestheelementfrom integerMapusingthedeletemethod.This methodremovestheelementfromthe integerMapoftheset,asfollows:
//deletestheelementfromthesetfunc(set*Set)DeleteElement(elementint){delete(set.integerMap,element)}
![Page 183: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/183.jpg)
TheContainsElementmethod
TheContainsElementmethodoftheSetclasscheckswhetherornottheelementexistsin integerMap.TheintegerMap elementislookedupwithakeyintegerelement,asshowninthefollowingcodeexample:
//checksifelementisinthesetfunc(set*Set)ContainsElement(elementint)bool{varexistsbool_,exists=set.integerMap[element]returnexists}
![Page 184: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/184.jpg)
Themainmethod–containselementInthefollowingcodesnippet,themainmethodcreates Set,invokestheNewmethod,andaddselements1and2.Thecheckisdoneifelement1existsintheset:
//mainmethodfuncmain(){varset*Setset=&Set{}set.New()set.AddElement(1)set.AddElement(2)fmt.Println(set)fmt.Println(set.ContainsElement(1))}
Runthefollowingcommandtoexecutetheset.gofile:gorunset.go
Afterexecutingtheprecedingcommand,wegetthefollowingoutput:
Let'stakealookattheInterSectmethodinthenextsection.
![Page 185: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/185.jpg)
TheInterSectmethod
Inthefollowingcode,theInterSectmethodonthe SetclassreturnsanintersectionSetthatconsistsoftheintersectionofsetandanotherSet.Theset classistraversedthroughintegerMapandcheckedagainstanotherSet toseeifanyelementsexist:
//IntersectmethodreturnsthesetwhichintersectswithanotherSet
func(set*Set)Intersect(anotherSet*Set)*Set{varintersectSet=&Set{}intersectSet.New()varvalueintfor(value,_=rangeset.integerMap){ifanotherSet.ContainsElement(value){intersectSet.AddElement(value)}}returnintersectSet}
TheexampleoutputafterinvokingtheintersectwiththeparameterofanotherSetisasfollows.AnewintersectSetiscreated.Thecurrentsetisiteratedandeveryvalueischeckedtoseeifitisinanotherset.Ifthevalueisinanotherset,itisaddedtothe set intersect:
Let'stakealookattheUnionmethodinthenextsection.
![Page 186: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/186.jpg)
TheUnionmethod
TheUnionmethodonthe SetclassreturnsaunionSetthatconsistsofaunionofsetandanotherSet.BothsetsaretraversedthroughintegerMapkeys,andunionsetisupdatedwithelementsfromthesets,asfollows:
//UnionmethodreturnsthesetwhichisunionofthesetwithanotherSet
func(set*Set)Union(anotherSet*Set)*Set{varunionSet=&Set{}unionSet.New()varvalueintfor(value,_=rangeset.integerMap){unionSet.AddElement(value)}
for(value,_=rangeanotherSet.integerMap){unionSet.AddElement(value)}
returnunionSet}
Theexampleoutputafterinvokingtheunionmethodwiththe anotherSet parameterisasfollows. AnewunionSetiscreated.Thecurrentsetandanothersetvaluesareiterated.Everyvalueisaddedtotheunionset:
Let'stakealookatthemainmethodinthenextsection.
![Page 187: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/187.jpg)
Themainmethod–intersectionandunion
Inthefollowingcodesnippet,themainmethodcallsintersectanduniononthesetclass,passingtheanotherSet parameter.Theintersectionandunionsetsareprintedasfollows:
//mainmethodfuncmain(){varset*Setset=&Set{}set.New()set.AddElement(1)set.AddElement(2)fmt.Println("initialset",set)fmt.Println(set.ContainsElement(1))varanotherSet*SetanotherSet=&Set{}anotherSet.New()anotherSet.AddElement(2)anotherSet.AddElement(4)anotherSet.AddElement(5)fmt.Println(set.Intersect(anotherSet))fmt.Println(set.Union(anotherSet))}
Themainmethodtakestwosetsandfindstheintersectionandunionofthesets.Runthefollowingcommandtoexecutetheset.gofile:
gorunset.go
Afterexecutingtheprecedingcommand,wegetthefollowingoutput:
![Page 188: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/188.jpg)
Thenextsectiontalksabouttuples,whicharefiniteorderedsequencesofobjects.
![Page 189: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/189.jpg)
TuplesTuplesarefiniteorderedsequencesofobjects.Theycancontainamixtureofotherdatatypesandareusedtogrouprelateddataintoadatastructure.Inarelationaldatabase,atupleisarowofatable.Tupleshaveafixedsizecomparedtolists,andarealsofaster. Afinitesetoftuplesintherelationaldatabaseisreferredtoasarelationinstance.Atuplecanbeassignedinasinglestatement,whichisusefulforswappingvalues. Listsusuallycontainvaluesofthesamedatatype,whiletuplescontaindifferentdata.Forexample,wecanstoreaname,age,andfavoritecolorofauserinatuple. TupleswerecoveredinChapter1,DataStructuresandAlgorithms.Thefollowingsampleshowsamulti-valuedexpressionfromafunction'scall(tuples.go):
//mainpackagehasexamplesshown//inHands-OnDataStructuresandalgorithmswithGobookpackagemain//importingfmtpackageimport("fmt")//hfunctionwhichreturnstheproductofparametersxandyfunch(xint,yint)int{returnx*y}//gfunctionwhichreturnsxandyparametersaftermodificationfuncg(lint,mint)(xint,yint){x=2*ly=4*mreturn}//mainmethodfuncmain(){fmt.Println(h(g()))}
Themainfunctioncallsthe hfunctionwiththegfunctionasitsparameter.The gfunctionreturnsthe tuplex andyintegers.Runthefollowingcommandtoexecutethetuples.gofile:
goruntuples.go
Afterexecutingtheprecedingcommand,wegetthefollowingoutput:
![Page 190: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/190.jpg)
Thenextsectiontalksaboutqueues,whicharelineardatastructures.
![Page 191: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/191.jpg)
QueuesAqueueconsistsofelementstobeprocessedinaparticularorderorbasedonpriority.Apriority-basedqueueofordersisshowninthefollowingcode,structuredasaheap.Operationssuchasenqueue,dequeue,andpeekcanbeperformedonqueue.Aqueueisalineardatastructureandasequentialcollection.Elementsareaddedtotheendandareremovedfromthestartofthecollection.Queuesarecommonlyusedforstoringtasksthatneedtobedone,orincomingHTTPrequeststhatneedtobeprocessedbyaserver.Inreallife,handlinginterruptionsinreal-timesystems,callhandling,andCPUtaskschedulingaregoodexamplesforusingqueues.ThefollowingcodeshowsthequeueofOrdersandhowthe Queuetypeisdefined:
//Queue—ArrayofOrdersTypetypeQueue[]*Order
//OrderclasstypeOrderstruct{priorityintquantityintproductstringcustomerNamestring}
Thefollowingsectionsinthechapterdiscussthe New,Add,andmainmethodsofqueue.
![Page 192: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/192.jpg)
TheNewmethod
TheNewmethodonthe Orderclassassignsthepropertiesfromthe priority,quantity,and product parametersfornameandcustomerName.Themethodinitializesthepropertiesoftheorderasfollows:
//NewmethodinitializeswithOrderwithpriority,quantity,product,customerNamefunc(order*Order)New(priorityint,quantityint,productstring,customerNamestring){order.priority=priorityorder.quantity=quantityorder.product=productorder.customerName=customerName}
![Page 193: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/193.jpg)
TheAddmethod
Inthefollowingcodesnippet,theAddmethodonthe Queueclasstakestheorderparameterandaddsit to Queuebasedonthepriority.Basedonthis,thelocationoftheorder parameterisfoundbycomparingitwiththepriority parameter:
//Addmethodaddstheordertothequeuefunc(queue*Queue)Add(order*Order){iflen(*queue)==0{*queue=append(*queue,order)}else{varappendedboolappended=falsevariintvaraddedOrder*Orderfori,addedOrder=range*queue{iforder.priority>addedOrder.priority{*queue=append((*queue)[:i],append(Queue{order},(*queue)[i:]...)...)appended=truebreak}}if!appended{*queue=append(*queue,order)}}}
Theexampleoutputaftertheaddmethodisinvokedwiththeorder parameterisasfollows. Theorderischeckedtoseewhetherornotitexistsinthequeue.Theorderisthenappendedtothequeue:
Let'stakealookattheMainmethodinthenextsection.
![Page 194: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/194.jpg)
Themainmethod–queuesThemainmethodcreatestwoorders,andthepriorityoftheordersissetto2and1.Inthefollowingcode,thequeuewillfirstprocesstheorderwiththehighernumberonthepriorityvalue:
//mainmethodfuncmain(){varqueueQueuequeue=make(Queue,0)varorder1*Order=&Order{}varpriority1int=2varquantity1int=20varproduct1string="Computer"varcustomerName1string="GregWhite"order1.New(priority1,quantity1,product1,customerName1)varorder2*Order=&Order{}varpriority2int=1varquantity2int=10varproduct2string="Monitor"varcustomerName2string="JohnSmith"order2.New(priority2,quantity2,product2,customerName2)queue.Add(order1)
queue.Add(order2)
variint
fori=0;i<len(queue);i++{
fmt.Println(queue[i])
}
}
Runthefollowingcommands toexecutethe queue.gofile:gorunqueue.go
Afterexecutingtheprecedingcommand,wegetthefollowingoutput:
![Page 195: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/195.jpg)
Let'stakealookatSynchronizedqueueinthenextsection.
![Page 196: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/196.jpg)
SynchronizedqueueAsynchronizedqueueconsistsofelements thatneedtobeprocessedinaparticularsequence.Passengerqueueandticketprocessingqueuesaretypesofsynchronized queues,asfollows:
//mainpackagehasexamplesshown//inHands-OnDataStructuresandalgorithmswithGobookpackagemain//importingfmtpackageimport("fmt""time""math/rand")//constantsconst(messagePassStart=iotamessageTicketStartmessagePassEndmessageTicketEnd)//QueueclasstypeQueuestruct{waitPassintwaitTicketintplayPassboolplayTicketboolqueuePasschanintqueueTicketchanintmessagechanint}
Wewilldiscussthedifferentmethodsofsynchronizedqueueinthefollowingsections.
![Page 197: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/197.jpg)
TheNewmethod
TheNewmethodonQueueinitializes message,queuePass,andqueueTicketwithnilvalues.ThemakemethodcreatesaQueuewitha chanintegerparameter, asfollows:
//Newmethodinitializesqueuefunc(queue*Queue)New(){queue.message=make(chanint)queue.queuePass=make(chanint)queue.queueTicket=make(chanint)}
Inthefollowingcodeexample,theGoroutinehandlesselectingthemessagebasedonthetypeofmessageandtherespectivequeuetoprocessit:
gofunc(){varmessageintfor{select{casemessage=<-queue.message:switchmessage{casemessagePassStart:queue.waitPass++casemessagePassEnd:queue.playPass=falsecasemessageTicketStart:queue.waitTicket++casemessageTicketEnd:queue.playTicket=false}ifqueue.waitPass>0&&queue.waitTicket>0&&!queue.playPass&&!queue.playTicket{queue.playPass=truequeue.playTicket=truequeue.waitTicket--queue.waitPass--queue.queuePass<-1queue.queueTicket<-1}}}}()}
![Page 198: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/198.jpg)
TheStartTicketIssuemethod TheStartTicketIssuemethodstartstheissuingofaticketforpassengersstandinginaqueue.The StartTicketIssuemethodonQueuesendsmessageTicketStarttothemessage queueandqueueTicketreceivesthemessage.Theticketissueisstartedbysendingmessagestothequeue,asfollows:
//StartTicketIssuestartstheticketissuefunc(Queue*Queue)StartTicketIssue(){Queue.message<-messageTicketStart<-Queue.queueTicket}
![Page 199: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/199.jpg)
TheEndTicketIssuemethod
TheEndTicketIssuemethodfinishestheissuingofatickettoapassengerstandinginthequeue.Inthefollowingcode,theEndTicketIssuemethodonQueuesendsmessageTicketEndtothemessage queue.Theticketissueisendedbysendingthemessage:
//EndTicketIssueendstheticketissuefunc(Queue*Queue)EndTicketIssue(){Queue.message<-messageTicketEnd}
![Page 200: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/200.jpg)
TheticketIssuemethod
TheticketIssuemethodstartsandfinishestheissuingofatickettothepassenger.The ticketIssuemethodinvokesthe StartTicketIssue andEndTicketIssue methodsafterSleepcallsfor10secondsandtwoseconds.Theticketisissuedaftertheticketisprocessed,asshowninthefollowingcode:
//ticketIssuestartsandendstheticketissuefuncticketIssue(Queue*Queue){for{//Sleepupto10seconds.time.Sleep(time.Duration(rand.Intn(10000))*time.Millisecond)Queue.StartTicketIssue()fmt.Println("TicketIssuestarts")//Sleepupto2seconds.time.Sleep(time.Duration(rand.Intn(2000))*time.Millisecond)fmt.Println("TicketIssueends")Queue.EndTicketIssue()}}
![Page 201: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/201.jpg)
TheStartPassmethod
TheStartPassmethodstartsthepassengerqueuemovingtowardtheticketcounter.TheStartPassmethodonQueuesendsmessagePassStarttothemessagequeueandqueuePassreceivesthemessage.Passengersaremovedintothequeueasfollows:
//StartPassendsthePassQueuefunc(Queue*Queue)StartPass(){Queue.message<-messagePassStart<-Queue.queuePass}
![Page 202: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/202.jpg)
TheEndPassmethod
TheEndPassmethodstopsthepassengerqueuemovingtowardtheticketcounter.TheEndPassmethodonQueuesendsmessagePassEndtothemessagequeueinthefollowingcode.Thepassengerismovedtothecounterforticketprocessing,andthepassengeristhenoutofthequeue:
//EndPassendsthePassQueuefunc(Queue*Queue)EndPass(){Queue.message<-messagePassEnd}
![Page 203: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/203.jpg)
Thepassengermethod
Thepassengermethodsstartsandendspassengermovementtothequeue.Thepassengermethodinvokesthe StartPass method,andthe EndPassmethodendsaftersleepcallsfor10secondsandtwoseconds.Thepassengermovesintothequeueandreachestheticketcounter,asshowninthefollowingcode:
//passengermethodstartsandendsthepassQueuefuncpassenger(Queue*Queue){//fmt.Println("startingthepassengerQueue")for{//fmt.Println("startingtheprocessing")//Sleepupto10seconds.time.Sleep(time.Duration(rand.Intn(10000))*time.Millisecond)Queue.StartPass()fmt.Println("Passengerstarts")//Sleepupto2seconds.time.Sleep(time.Duration(rand.Intn(2000))*time.Millisecond)fmt.Println("Passengerends")Queue.EndPass()}}
![Page 204: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/204.jpg)
Themainmethod
ThemainmethodcallsthepassengerandticketIssuemethodsaftercreatingaqueue.Thepassengerentersintothequeueandaticketisissuedatthecounterintheprocessing queue,asexplainedinthefollowingcode:
//mainmethodfuncmain(){varQueue*Queue=&Queue{}//fmt.Println(Queue)Queue.New()fmt.Println(Queue)variintfori=0;i<10;i++{//fmt.Println(i,"passengerintheQueue")gopassenger(Queue)}//close(Queue.queuePass)varjintforj=0;j<5;j++{//fmt.Println(i,"ticketissuedintheQueue")goticketIssue(Queue)}select{}}
Runthefollowingcommand toexecutethe sync_queue.gofile:gorunsync_queue.go
Afterexecutingtheprecedingcommand,wegetthefollowingoutput:
![Page 205: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/205.jpg)
ThenextsectiontalksaboutStacks,whicharelineardatastructures.
![Page 206: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/206.jpg)
StacksAstackisalastin,firstoutstructureinwhichitemsareaddedfromthetop. Stacksareusedinparsersforsolvingmazealgorithms. Push,pop,top,andgetsizearethetypicaloperationsthatareallowedonstackdatastructures.Syntaxparsing,backtracking,andcompilingtimememorymanagementaresomereal-lifescenarioswherestackscanbeused.Anexampleofstackimplementationisasfollows(stack.go):
//mainpackagehasexamplesshown//inHands-OnDataStructuresandalgorithmswithGobookpackagemain//importingfmtpackageimport("fmt""strconv")//ElementclasstypeElementstruct{elementValueint}//StringmethodonElementclassfunc(element*Element)String()string{returnstrconv.Itoa(element.elementValue)}
TheElementclasshaselementValueasanattribute.TheString methodreturnstheelement'selementValue.Stacksmethods,suchasNew,Push,Pop,andmain arepresentedinthefollowingsections.
![Page 207: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/207.jpg)
TheNewmethod
TheNewmethodonthe Stackclasscreatesadynamicarrayofelements.TheStackclasshasthecountandarraypointerofelements.ThecodesnippetwiththeStackclassdefinitionandthe Newmethodisasfollows:
//NewStackreturnsanewstack.func(stack*Stack)New(){stack.elements=make(*Element[]elements,0)}//StackisabasicLIFOstackthatresizesasneeded.typeStackstruct{elements[]*ElementelementCountint}
![Page 208: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/208.jpg)
ThePushmethod
ThePushmethodaddsthenodetothetopofthestack class.Inthefollowingcodesample,the Pushmethodonthe Stackclassaddstheelementtotheelementsarrayandincreasesthe Count element,whiletheappendmethodaddstheelementtotheelementsofthestack class:
//Pushaddsanodetothestack.func(stack*Stack)Push(element*Element){stack.elements=append(stack.elements[:stack.elementCount],element)stack.elementCount=stack.elementCount+1}
Theexampleoutputafterthepushmethodisinvokedwithparameterelementsasfollows.Theelementwiththevalue7ispushedtothestack.Thecountoftheelementsbeforepushingtothestackis2,and,afterpushingtothestack,thisfigureis3:
Let'stakealookatthePopmethodinthenextsection.
![Page 209: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/209.jpg)
ThePopmethod
ThePopmethodonthe Stackimplementationremovesthelastelementfromtheelementarrayandreturnstheelement,asshowninthefollowingcode.Thelenmethodreturnsthelengthoftheelementsarray:
//Popremovesandreturnsanodefromthestackinlasttofirstorder.func(stack*Stack)Pop()*Element{ifstack.elementCount==0{returnnil}varlengthint=len(stack.elements)varelement*Element=stack.elements[length-1]//stack.elementCount=stack.elementCount-1iflength>1{stack.elements=stack.elements[:length-1]}else{stack.elements=stack.elements[0:]}stack.elementCount=len(stack.elements)returnelement}
TheexampleoutputafterthePopmethodisinvokedisasfollows.Theelementvalue5ispassedandaddedtothe Pop method.ThecountofelementsbeforeinvokingthePopmethodis2.Thecountoftheelementsaftercallingthe Popmethodis1:
Let'stakealookatthemainmethodinthenextsection.
![Page 210: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/210.jpg)
Themainmethod
Inthefollowingcodesection,themainmethodcreatesastack,callstheNewmethod,andpushestheelementsafterinitializingthem.Thepopped-outelementvalueandtheorderisprinted:
//mainmethodfuncmain(){varstack*Stack=&Stack{}stack.New()varelement1*Element=&Element{3}varelement2*Element=&Element{5}varelement3*Element=&Element{7}varelement4*Element=&Element{9}stack.Push(element1)stack.Push(element2)stack.Push(element3)stack.Push(element4)fmt.Println(stack.Pop(),stack.Pop(),stack.Pop(),stack.Pop())}
Runthefollowingcommands toexecutethestack.gofile:gorunstack.go
Afterexecutingtheprecedingcommand,wegetthefollowingoutput:
![Page 211: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/211.jpg)
SummaryThischaptercoveredthedefinitionofLinkedList,doubleLinkedList,Tuples,Sets,Queues,andStacks.The LinkedListmethods– AddToHead,AddToEnd,LastNode,anditerateList—werealsocoveredinthischapter.Inaddition,apriorityqueuewasmodeledasaheapoforderstobeprocessed,syncqueuewaspresentedaspassengerandticketprocessingqueues,andtupleswereexplainedinacontextinwhichafunctionreturnsamultivaluedexpression.Thenew,push,pop,andstringmethodsforStack wereexplainedwithcodesamples.Inthenextchapter,wewillcoverareassuchasthe Trees,Tables,Containers,andHashfunctions.
![Page 212: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/212.jpg)
Questions1. Wherecanyouusedoublelinkedlist?Pleaseprovideanexample.2. Whichmethodonlinkedlistcanbeusedforprintingoutnodevalues?3. WhichqueuewasshownwithchannelsfromtheGolanguage?4. Writeamethodthatreturnsmultiplevalues.Whatdatastructurecanbeusedforreturningmultiplevalues?
5. Cansethaveduplicateelements?6. Writeacode sampleshowingtheunionandintersectionoftwosets.7. Inalinkedlist,whichmethodisusedtofindthenodebetweentwovalues?
8. Wehaveelementsthatarenotrepeatedandunique.Whatisthecorrectdatastructurethatrepresentsthecollection?
9. InGo,howdoyougeneratearandomintegerbetweenthevalues3and5?
10. Whichmethodiscalledtocheckifanelementofvalue5existsintheSet?
![Page 213: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/213.jpg)
Furtherreading
ToreadmoreaboutLinkedLists,Sets,Tuples,andStacks,consultthefollowingsources:
DesignPatterns, byErichGamma,RichardHelm,RalphJohnson,andJohnVlissidesIntroductiontoAlgorithms –ThirdEdition,byThomasH.Cormen,CharlesE.Leiserson,RonaldL.Rivest,andCliffordSteinDatastructuresandAlgorithms:AnEasyIntroduction,by RudolphRussell
![Page 214: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/214.jpg)
Non-LinearDataStructuresNon-lineardatastructuresareusedincryptographyandotherareas.Anon-lineardatastructureisanarrangementinwhichanelementis connectedtomanyelements.Thesestructuresusememoryquicklyandefficiently.Freecontiguousmemoryisnotrequiredforaddingnewelements.Thelengthofthedatastructuresisnotimportantbeforeaddingnewelements.Anon-lineardatastructurehasmultiplelevelsandalinearonehasasinglelevel.Thevaluesoftheelementsarenotorganizedinanon-lineardatastructure.Thedataelementsinanon-lineardatastructurecannotbeiteratedinonestep.Theimplementationofthesedatastructuresiscomplicated.Treetypessuchasbinarysearchtrees,treaps,andsymboltablesareexplainedinthischapter. Thischaptercoversthefollowingnon-lineardatastructures:
TreesTablesContainersHashfunctions
![Page 215: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/215.jpg)
TechnicalrequirementsInstallGoversion1.10fromhttps://golang.org/doc/install foryourOS.TheGitHubURLforthecodeinthischapterisasfollows: https://github.com/PacktPublishing/Learn-Data-Structures-and-Algorithms-with-Golang/tree/master/Chapter04.
![Page 216: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/216.jpg)
TreesAtreeisanon-lineardatastructure. Treesareusedforsearchandotherusecases.Abinarytreehasnodesthathaveamaximumoftwochildren.Abinarysearchtreeconsistsofnodeswherethepropertyvaluesoftheleftnodearelessthanthepropertyvaluesoftherightnode.Therootnodeisatlevelzeroofatree.Eachchildnodecouldbealeaf.Treesandbinarytrees wereintroducedin Chapter1,DataStructuresandAlgorithms,whilewewerediscussinglogarithmiccomplexity. Let'stakeacloserlookattheminthenextsection.
![Page 217: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/217.jpg)
BinarysearchtreeAbinarysearchtreeisadatastructurethatallowsforthequicklookup,addition,andremovalofelements.Itstoresthekeysinasortedordertoenableafasterlookup.Thisdatastructurewasinventedby P.F.Windley,A.D.Booth,A.J.T.Colin,andT.N.Hibbard.Onaverage,spaceusageforabinarysearchtreeisoftheorderO(n),whereastheinsert,search,anddeleteoperationsareoftheorderO(logn). Abinarysearchtreeconsistsofnodes withpropertiesorattributes:
AkeyintegerAvalueintegerTheleftNodeandrightNodeinstances of TreeNode
Theycanberepresentedinthefollowingcode://TreeNodeclasstypeTreeNodestruct{keyintvalueintleftNode*TreeNoderightNode*TreeNode}
Inthenextsection,the BinarySearchTreeclassimplementationisdiscussed.Forthissection,pleaserefertothebinary_search_tree.gofile.
![Page 218: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/218.jpg)
TheBinarySearchTreeclassInthefollowingcodesnippet,theBinarySearchTreeclassconsistsofa rootNodethat'softheTreeNodetype,andlock,whichisofthesync.RWMutextype.ThebinarysearchtreeistraversedfromrootNodebyaccessingthenodestotheleftandright ofrootNode:
//BinarySearchTreeclasstypeBinarySearchTreestruct{rootNode*TreeNodelocksync.RWMutex}
Nowthatweknowwhat BinarySearchTreeis,let'stakealookatitsdifferentmethodsinthenextsection.
![Page 219: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/219.jpg)
TheInsertElementmethod
TheInsertElementmethodinsertstheelementwiththegivenkeyandvalueinthebinarysearchtree.Thetree'slock()instanceislockedfirstandtheunlock()methodisdeferredbeforeinsertingtheelement.TheInsertTreeNodemethodisinvokedbypassingrootNodeandthenodetobecreatedwiththekeyandvalue,asshownhere:
//InsertElementmethodfunc(tree*BinarySearchTree)InsertElement(keyint,valueint){tree.lock.Lock()defertree.lock.Unlock()vartreeNode*TreeNodetreeNode=&TreeNode{key,value,nil,nil}iftree.rootNode==nil{tree.rootNode=treeNode}else{insertTreeNode(tree.rootNode,treeNode)}}
Theexampleoutputforinsertinganelementwithkeyandvalue3isshownasfollows.TheinsertelementmethodcallsinsertTreeNodewithrootNode withkey8andthenewtreeNodewithkey3:
![Page 220: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/220.jpg)
TheinsertTreeNodemethod
TheinsertTreenodemethodinsertsthenewTreeNodeinthebinarysearchtree. Inthefollowingcode,theinsertTreeNodemethodtakesrootNodeandnewTreeNode,bothoftheTreeNodetype,asparameters.Notethat newTreeNodeisinsertedattherightplaceinthebinarysearchtreebycomparingthekeyvalues:
//insertTreeNodefunctionfuncinsertTreeNode(rootNode*TreeNode,newTreeNode*TreeNode){ifnewTreeNode.key<rootNode.key{ifrootNode.leftNode==nil{rootNode.leftNode=newTreeNode}else{insertTreeNode(rootNode.leftNode,newTreeNode)}}else{ifrootNode.rightNode==nil{rootNode.rightNode=newTreeNode}else{insertTreeNode(rootNode.rightNode,newTreeNode)}}}
![Page 221: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/221.jpg)
TheinOrderTraversemethod
TheinOrderTraversemethodvisitsallnodes inorder.TheRLock() methodonthetree lockinstanceiscalledfirst.TheRUnLock()methodisdeferredonthetree lockinstancebeforeinvokingtheinOrderTraverseTreemethod,aspresentedinthefollowingcodesnippet:
//InOrderTraverseTreemethodfunc(tree*BinarySearchTree)InOrderTraverseTree(functionfunc(int)){tree.lock.RLock()defertree.lock.RUnlock()inOrderTraverseTree(tree.rootNode,function)}
![Page 222: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/222.jpg)
TheinOrderTraverseTreemethod
TheinOrderTraverseTreemethodtraversestheleft,theroot,andtherighttree.TheinOrderTraverseTreemethodtakestreeNodeoftheTreeNodetypeand functionasparameters.TheinOrderTraverseTreemethodiscalledonleftNodeandrightNodewithfunctionasaparameter.AfunctionispassedwithtreeNode.value,asshowninthefollowingcodesnippet:
//inOrderTraverseTreemethodfuncinOrderTraverseTree(treeNode*TreeNode,functionfunc(int)){iftreeNode!=nil{inOrderTraverseTree(treeNode.leftNode,function)function(treeNode.value)inOrderTraverseTree(treeNode.rightNode,function)}}
![Page 223: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/223.jpg)
ThePreOrderTraverseTreemethod
ThePreOrderTraverseTreemethodvisitsallthe treenodeswithpreordertraversing.Thetree lockinstanceislockedfirstandtheUnlockmethodisdeferredbeforepreOrderTraverseTreeiscalled.Inthefollowingcodesnippet,thepreOrderTraverseTreemethodispassedwithrootNodeandfunctionasparameters:
//PreOrderTraverseTreemethodfunc(tree*BinarySearchTree)PreOrderTraverseTree(functionfunc(int)){tree.lock.Lock()defertree.lock.Unlock()preOrderTraverseTree(tree.rootNode,function)}
![Page 224: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/224.jpg)
ThepreOrderTraverseTreemethod
ThepreOrderTraverseTreemethodispassedwithtreeNodeoftheTreeNodetypeandfunctionasparameters.ThepreOrderTraverseTreemethodiscalledbypassingleftNodeandrightNodewithfunctionasparameters.The function isinvokedwithtreeNode.value,asshownhere:
//preOrderTraverseTreemethodfuncpreOrderTraverseTree(treeNode*TreeNode,functionfunc(int)){iftreeNode!=nil{function(treeNode.value)preOrderTraverseTree(treeNode.leftNode,function)preOrderTraverseTree(treeNode.rightNode,function)}}
![Page 225: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/225.jpg)
ThePostOrderTraverseTreemethod
ThePostOrderTraverseTreemethodtraversesthenodesinapostorder(left,right,currentnode).Inthefollowingcodesnippet,thePostOrderTraverseTreemethodoftheBinarySearchTreeclassvisitsallnodeswithpost-ordertraversing.Thefunction methodispassedasaparametertothemethod.Thetree.lockinstanceislockedfirstandtheUnlockmethodisdeferredonthetree lockinstancebeforecallingthepostOrderTraverseTreemethod:
//PostOrderTraverseTreemethodfunc(tree*BinarySearchTree)PostOrderTraverseTree(functionfunc(int)){tree.lock.Lock()defertree.lock.Unlock()postOrderTraverseTree(tree.rootNode,function)}
![Page 226: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/226.jpg)
ThepostOrderTraverseTreemethod
ThepostOrderTraverseTreemethodispassedwithtreeNodeoftheTreeNodetypeandfunctionasparameters.ThepostOrderTraverseTreemethodiscalledbypassingleftNodeandrightNodewithfunctionasparameters.Inthefollowingcodesnippet,functionisinvokedwithtreeNode.valueasaparameter:
//postOrderTraverseTreemethodfuncpostOrderTraverseTree(treeNode*TreeNode,functionfunc(int)){iftreeNode!=nil{postOrderTraverseTree(treeNode.leftNode,function)postOrderTraverseTree(treeNode.rightNode,function)function(treeNode.value)}}
![Page 227: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/227.jpg)
TheMinNodemethod
MinNodefindsthenodewiththeminimumvalueinthebinarysearchtree. Inthefollowingcodesnippet,theRLockmethodofthetree lockinstanceisinvokedfirstandtheRUnlockmethodonthetree lockinstanceisdeferred.TheMinNodemethodreturnstheelementwiththelowestvaluebytraversingfromrootNodeandcheckingwhetherthevalueofleftNodeisnil:
//MinNodemethodfunc(tree*BinarySearchTree)MinNode()*int{tree.lock.RLock()defertree.lock.RUnlock()vartreeNode*TreeNodetreeNode=tree.rootNodeiftreeNode==nil{//nilinsteadof0return(*int)(nil)}for{iftreeNode.leftNode==nil{return&treeNode.value}treeNode=treeNode.leftNode}}
![Page 228: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/228.jpg)
TheMaxNodemethod
MaxNodefindsthenodewithmaximumpropertyinthebinarysearchtree. TheRLockmethodofthetree lockinstanceiscalledfirstandtheRUnlockmethodonthetree lockinstanceisdeferred.TheMaxNodemethodreturnstheelementwiththehighestvalueaftertraversingfromrootNodeandfindingarightNodewithanilvalue.Thisisshowninthefollowingcode:
//MaxNodemethodfunc(tree*BinarySearchTree)MaxNode()*int{tree.lock.RLock()defertree.lock.RUnlock()vartreeNode*TreeNodetreeNode=tree.rootNodeiftreeNode==nil{//nilinsteadof0return(*int)(nil)}for{iftreeNode.rightNode==nil{return&treeNode.value}treeNode=treeNode.rightNode}}
![Page 229: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/229.jpg)
TheSearchNodemethod
TheSearchNodemethodsearchesthespecifiednodeinthebinarysearchtree.First,theRLockmethodofthetreelockinstanceiscalled.Then,theRUnlockmethodonthetree lockinstanceisdeferred.TheSearchNodemethodoftheBinarySearchTreeclassinvokesthesearchNodemethodwiththerootNodeandthe keyintegervalueas parameters, asshownhere:
//SearchNodemethodfunc(tree*BinarySearchTree)SearchNode(keyint)bool{tree.lock.RLock()defertree.lock.RUnlock()returnsearchNode(tree.rootNode,key)}
![Page 230: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/230.jpg)
ThesearchNodemethod
Inthefollowingcode,thesearchNodemethodtakestreeNode,apointeroftheTreeNodetype,andakeyintegervalueasparameters.Themethodreturnstrueorfalseaftercheckingwhether treeNodewiththesamevalueas keyexists:
//searchNodemethodfuncsearchNode(treeNode*TreeNode,keyint)bool{iftreeNode==nil{returnfalse}ifkey<treeNode.key{returnsearchNode(treeNode.leftNode,key)}ifkey>treeNode.key{returnsearchNode(treeNode.rightNode,key)}returntrue}
![Page 231: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/231.jpg)
TheRemoveNodemethod
TheRemoveNodemethodoftheBinarySearchTreeclassremovestheelementwith keythat'spassedin.Themethodtakesthekeyintegervalueastheparameter.TheLock()methodisinvokedonthetree'slockinstancefirst.TheUnlock()methodofthetree lockinstanceisdeferred,andremoveNodeiscalledwithrootNodeandthekeyvalueasparameters,asshownhere:
//RemoveNodemethodfunc(tree*BinarySearchTree)RemoveNode(keyint){tree.lock.Lock()defertree.lock.Unlock()removeNode(tree.rootNode,key)}
![Page 232: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/232.jpg)
TheremoveNodemethod
TheremoveNodemethodtakestreeNodeoftheTreeNodetypeanda keyintegervalueasparameters.Inthefollowingcodesnippet,themethodrecursivelysearchesthe leftNodeinstanceoftreeNodeandthekeyvalueofrightNode ifitmatchestheparametervalue:
//removeNodemethodfuncremoveNode(treeNode*TreeNode,keyint)*TreeNode{iftreeNode==nil{returnnil}ifkey<treeNode.key{treeNode.leftNode=removeNode(treeNode.leftNode,key)returntreeNode}ifkey>treeNode.key{treeNode.rightNode=removeNode(treeNode.rightNode,key)returntreeNode}//key==node.keyiftreeNode.leftNode==nil&&treeNode.rightNode==nil{treeNode=nilreturnnil}iftreeNode.leftNode==nil{treeNode=treeNode.rightNodereturntreeNode}iftreeNode.rightNode==nil{treeNode=treeNode.leftNodereturntreeNode}varleftmostrightNode*TreeNodeleftmostrightNode=treeNode.rightNodefor{//findsmallestvalueontherightsideifleftmostrightNode!=nil&&leftmostrightNode.leftNode!=nil{leftmostrightNode=leftmostrightNode.leftNode}else{break}}treeNode.key,treeNode.value=leftmostrightNode.key,leftmostrightNode.valuetreeNode.rightNode=removeNode(treeNode.rightNode,treeNode.key)returntreeNode}
![Page 233: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/233.jpg)
TheStringmethod
TheStringmethodturnsthetreeintoastringformat. Atfirst,theLock()methodisinvokedonthetree lockinstance.Then,theUnlock()methodofthetree lockinstanceisdeferred.TheStringmethodprintsavisualrepresentationoftree:
//Stringmethodfunc(tree*BinarySearchTree)String(){tree.lock.Lock()defertree.lock.Unlock()fmt.Println("------------------------------------------------")stringify(tree.rootNode,0)fmt.Println("------------------------------------------------")}
![Page 234: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/234.jpg)
Thestringifymethod
Inthefollowingcodesnippet,thestringifymethodtakesatreeNodeinstanceoftheTreeNodetypeandlevel (an integer)asparameters.Themethodrecursivelyprintsthetreebasedonthelevel:
//stringifymethodfuncstringify(treeNode*TreeNode,levelint){iftreeNode!=nil{format:=""fori:=0;i<level;i++{format+=""}format+="---["level++stringify(treeNode.leftNode,level)fmt.Printf(format+"%d\n",treeNode.key)stringify(treeNode.rightNode,level)}}
![Page 235: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/235.jpg)
Themainmethod
Inthefollowingcode,themainmethodcreatesthebinarysearchtreeandinsertstheelements8,3,10,1,and6intoit.treeisprintedbyinvokingtheStringmethod:
//mainmethodfuncmain(){vartree*BinarySearchTree=&BinarySearchTree{}tree.InsertElement(8,8)tree.InsertElement(3,3)tree.InsertElement(10,10)tree.InsertElement(1,1)tree.InsertElement(6,6)tree.String()}
Runthefollowingcommandtoexecutethebinary_search_tree.gofile:gorunbinary_search_tree.go
Theoutputisasfollows:
ThenextsectiontalksaboutAVLtreeimplementation.
![Page 236: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/236.jpg)
Adelson,Velski,andLandis(AVL)treeAdelson,Velski,andLandispioneeredtheAVLtreedatastructureandhenceitisnamedafterthem.Itconsistsofheightadjustingbinarysearchtrees.Thebalancefactorisobtainedbyfindingthedifferencebetweentheheightsoftheleftandrightsub-trees. Balancingisdoneusingrotationtechniques.Ifthebalancefactorisgreaterthanone,rotationshiftsthenodestotheoppositeoftheleftorrightsub-trees.Thesearch,addition,anddeletionoperationsareprocessedintheorderofO(log n).Thefollowingsectionstalksaboutthe KeyValue interfacedefinitionandthe TreeNodeclass. Forthissection,pleaserefertotheavl_tree.gofile.
![Page 237: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/237.jpg)
TheKeyValueinterfaceTheKeyValueinterfacehasthe LessThanandEqualTomethods.TheLessThanandEqualTomethodstakeKeyValueasaparameterandreturnaBooleanvalueaftercheckingthelessthanorequaltocondition.Thisisshowninthefollowingcode:
//KeyValuetypetypeKeyValueinterface{LessThan(KeyValue)boolEqualTo(KeyValue)bool}
![Page 238: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/238.jpg)
TheTreeNodeclassTheTreeNodeclasshasKeyValue,BalanceValue,andLinkedNodesasproperties.TheAVLtreeiscreatedasatreeofnodesoftheTreeNodetype,asshownhere:
//TreeNodeclasstypeTreeNodestruct{KeyValueKeyValueBalanceValueintLinkedNodes[2]*TreeNode}
Now,let'stakealookatthedifferentmethodsofthe TreeNodeclass.
![Page 239: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/239.jpg)
Theoppositemethod
Theoppositemethodtakesanodevalueandreturnstheoppositenode'svalue.Inthefollowingcodesnippet,theoppositemethodtakesthenodeValueintegerasaparameterandreturnstheoppositenode'svalue:
//oppositemethodfuncopposite(nodeValueint)int{return1-nodeValue}
![Page 240: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/240.jpg)
ThesingleRotationmethod
ThesingleRotationmethodrotatesthenodeoppositetothespecified sub-tree.Asshowninthefollowingsnippet,thesingleRotationfunctionrotatesthenode oppositetheleftorrightsub-tree.Themethodtakesthepointerto rootNodeandanodeValueinteger asparametersandreturnsaTreeNodepointer:
//singlerotationmethodfuncsingleRotation(rootNode*TreeNode,nodeValueint)*TreeNode{varsaveNode*TreeNodesaveNode=rootNode.LinkedNodes[opposite(nodeValue)]rootNode.LinkedNodes[opposite(nodeValue)]=saveNode.LinkedNodes[nodeValue]saveNode.LinkedNodes[nodeValue]=rootNodereturnsaveNode}
![Page 241: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/241.jpg)
ThedoubleRotationmethod
Here,thedoubleRotationmethodrotatesthenodetwice.ThemethodreturnsaTreeNodepointer,takingparameterssuchasrootNode,whichisatreeNodepointer,andnodeValue,whichisaninteger.Thisisshowninthefollowingcode:
//doublerotationfuncdoubleRotation(rootNode*TreeNode,nodeValueint)*TreeNode{varsaveNode*TreeNodesaveNode=rootNode.LinkedNodes[opposite(nodeValue)].LinkedNodes[nodeValue]rootNode.LinkedNodes[opposite(nodeValue)].LinkedNodes[nodeValue]=saveNode.LinkedNodes[opposite(nodeValue)]saveNode.LinkedNodes[opposite(nodeValue)]=rootNode.LinkedNodes[opposite(nodeValue)]rootNode.LinkedNodes[opposite(nodeValue)]=saveNodesaveNode=rootNode.LinkedNodes[opposite(nodeValue)]rootNode.LinkedNodes[opposite(nodeValue)]=saveNode.LinkedNodes[nodeValue]saveNode.LinkedNodes[nodeValue]=rootNodereturnsaveNode}
TheimplementationofthismethodisshowninTheInsertNodemethodsection,asfollows.
![Page 242: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/242.jpg)
TheadjustBalancemethod
TheadjustBalancemethodadjuststhebalanceofthetree.Inthefollowingcodesnippet,theadjustBalancemethoddoesadoublerotationgiventhebalancefactor,rootNode,andnodeValue.TheadjustBalancemethodtakesrootNode,whichisaninstanceoftheTreeNodetype,nodeValue,andbalanceValue(whicharebothintegers) asparameters:
//adjustbalancemethodfuncadjustBalance(rootNode*TreeNode,nodeValueint,balanceValueint){varnode*TreeNodenode=rootNode.LinkedNodes[nodeValue]varoppNode*TreeNodeoppNode=node.LinkedNodes[opposite(balanceValue)]switchoppNode.BalanceValue{case0:rootNode.BalanceValue=0node.BalanceValue=0casebalanceValue:rootNode.BalanceValue=-balanceValuenode.BalanceValue=0default:rootNode.BalanceValue=0node.BalanceValue=balanceValue}oppNode.BalanceValue=0}
![Page 243: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/243.jpg)
TheBalanceTreemethod
TheBalanceTreemethodchangesthebalancefactorbyasingleordoublerotation.ThemethodtakesrootNode(aTreeNodepointer)andnodeValue (an integer)as parameters.TheBalanceTreemethodreturnsaTreeNodepointer,asshownhere:
//BalanceTreemethodfuncBalanceTree(rootNode*TreeNode,nodeValueint)*TreeNode{varnode*TreeNodenode=rootNode.LinkedNodes[nodeValue]varbalanceintbalance=2*nodeValue-1ifnode.BalanceValue==balance{rootNode.BalanceValue=0node.BalanceValue=0returnsingleRotation(rootNode,opposite(nodeValue))}adjustBalance(rootNode,nodeValue,balance)returndoubleRotation(rootNode,opposite(nodeValue))}
![Page 244: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/244.jpg)
TheinsertRNodemethod
TheinsertRNodemethodinsertsthenodeandbalancesthetree.Thismethod inserts rootNodewiththe KeyValuekey,aspresentedinthefollowingcodesnippet.ThemethodtakesrootNode,whichisaTreeNodepointer,andthekeyasanintegeras parameters.ThemethodreturnsaTreeNodepointerandaBooleanvalueiftherootNodeisinserted:
//insertRNodemethodfuncinsertRNode(rootNode*TreeNode,keyKeyValue)(*TreeNode,bool){ifrootNode==nil{return&TreeNode{KeyValue:key},false}vardirintdir=0ifrootNode.KeyValue.LessThan(key){dir=1}vardoneboolrootNode.LinkedNodes[dir],done=insertRNode(rootNode.LinkedNodes[dir],key)ifdone{returnrootNode,true}rootNode.BalanceValue=rootNode.BalanceValue+(2*dir-1)switchrootNode.BalanceValue{case0:returnrootNode,truecase1,-1:returnrootNode,false}returnBalanceTree(rootNode,dir),true}
![Page 245: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/245.jpg)
TheInsertNodemethod
TheInsertNodemethodinsertsanodeintotheAVLtree. This methodtakestreeNode,whichisadoubleTreeNodepointer,andthe keyvalueasparameters:
//InsertNodemethodfuncInsertNode(treeNode**TreeNode,keyKeyValue){*treeNode,_=insertRNode(*treeNode,key)}
Theexampleoutputofthe InsertNodemethodisshowninthefollowingscreenshot.TheInsertNodemethodcallsthe insertRNodemethodwiththe rootNode parametersandnodetobeinserted.rootNodehasakeyvalueof 5andthenodetobeinsertedhasakeyvalueof 6.Thetreeneedstobebalanced.Hence,thenextcallwillberootNodewithkey8andnodetobeinserted.Thenextstepcallsrootnodewithkeyvalue7andnodetobeinserted.ThelastcallwillbewithrootNodenilandnodetobeinserted.Thebalancevalueischeckedandthebalancetreemethodreturnsthebalancedtree:
![Page 246: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/246.jpg)
TheRemoveNodemethod
Inthefollowingcode,theRemoveNodemethodremovestheelementfromtheAVLtreebyinvokingtheremoveRNodemethod.ThemethodtakestreeNode,whichisadoubleTreeNodepointer,and KeyValueas parameters:
//RemoveNodemethodfuncRemoveNode(treeNode**TreeNode,keyKeyValue){*treeNode,_=removeRNode(*treeNode,key)}
![Page 247: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/247.jpg)
TheremoveBalancemethod
TheremoveBalancemethodremovesthebalancefactorinatree.This methodadjuststhebalancefactorafterremovingthenodeandreturnsatreeNodepointerandaBooleanifthebalanceisremoved.ThemethodtakesrootNode(aninstanceofTreeNode)andnodeValue(aninteger)asparameters.Thisisshowninthefollowingcode:
//removeBalancemethodfuncremoveBalance(rootNode*TreeNode,nodeValueint)(*TreeNode,bool){varnode*TreeNodenode=rootNode.LinkedNodes[opposite(nodeValue)]varbalanceintbalance=2*nodeValue-1switchnode.BalanceValue{case-balance:rootNode.BalanceValue=0node.BalanceValue=0returnsingleRotation(rootNode,nodeValue),falsecasebalance:adjustBalance(rootNode,opposite(nodeValue),-balance)returndoubleRotation(rootNode,nodeValue),false}rootNode.BalanceValue=-balancenode.BalanceValue=balancereturnsingleRotation(rootNode,nodeValue),true}
![Page 248: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/248.jpg)
TheremoveRNodemethod
TheremoveRNode methodremovesthenodefromthetreeandbalancesthetree.This methodtakesrootNode,whichisaTreeNodepointer,andthe keyvalue.ThismethodreturnsaTreeNodepointerandBooleanvalueifRNode isremoved,asshowninthefollowingcodesnippet:
//removeRNodemethodfuncremoveRNode(rootNode*TreeNode,keyKeyValue)(*TreeNode,bool){ifrootNode==nil{returnnil,false}ifrootNode.KeyValue.EqualTo(key){switch{caserootNode.LinkedNodes[0]==nil:returnrootNode.LinkedNodes[1],falsecaserootNode.LinkedNodes[1]==nil:returnrootNode.LinkedNodes[0],false}varheirNode*TreeNodeheirNode=rootNode.LinkedNodes[0]forheirNode.LinkedNodes[1]!=nil{heirNode=heirNode.LinkedNodes[1]}rootNode.KeyValue=heirNode.KeyValuekey=heirNode.KeyValue}vardirintdir=0ifrootNode.KeyValue.LessThan(key){dir=1}vardoneboolrootNode.LinkedNodes[dir],done=removeR(rootNode.LinkedNodes[dir],key)ifdone{returnrootNode,true}rootNode.BalanceValue=rootNode.BalanceValue+(1-2*dir)switchrootNode.BalanceValue{case1,-1:returnrootNode,truecase0:returnrootNode,false}returnremoveBalance(rootNode,dir)}typeintegerKeyintfunc(kintegerKey)LessThan(k1KeyValue)bool{returnk<k1.(integerKey)}func(kintegerKey)EqualTo(k1KeyValue)bool{returnk==k1.(integerKey)}
Theexampleoutputofthe removeRNodemethodisshownasfollows.TheRemoveNodemethodcallstheremoveRNodemethod.TheremoveRNodemethod
![Page 249: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/249.jpg)
RemoveNodemethodcallstheremoveRNodemethod.TheremoveRNodemethodtakestheparameters,suchasrootNodeandKeyValue,ofthenode:
![Page 250: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/250.jpg)
Themainmethod
Inthefollowingcodesnippet,themainmethodcreatesanAVLtreebyinsertingnodeswiththe 5,3,8,7,6,and10 keys.Nodeswiththe 3and7 keysareremoved.ThetreedatastructureisconvertedintoJSONinbytes.TheJSONbytesareprintedafterbeingchangedtoastring:
//mainmethodfuncmain(){vartreeNode*TreeNodefmt.Println("Treeisempty")varavlTree[]byteavlTree,_=json.MarshalIndent(treeNode,"","")fmt.Println(string(avlTree))
fmt.Println("\nAddTree")InsertNode(&treeNode,integerKey(5))InsertNode(&treeNode,integerKey(3))InsertNode(&treeNode,integerKey(8))InsertNode(&treeNode,integerKey(7))InsertNode(&treeNode,integerKey(6))InsertNode(&treeNode,integerKey(10))avlTree,_=json.MarshalIndent(treeNode,"","")fmt.Println(string(avlTree))
fmt.Println("\nDeleteTree")RemoveNode(&treeNode,integerKey(3))RemoveNode(&treeNode,integerKey(7))avlTree,_=json.MarshalIndent(treeNode,"","")fmt.Println(string(avlTree))}
Runthefollowingcommandtoexecutetheavl_tree.gofile:gorunavl_tree.go
Theoutputisasfollows:
![Page 251: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/251.jpg)
Inthenextsection,B+treeimplementationisdiscussedandcodesnippetsarepresented.
![Page 252: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/252.jpg)
B+treeTheB+treecontainsalistofkeysandpointerstothenext-levelnodesintrees.Duringasearch,recursionisusedtosearchforanelementbylookingforthe theadjacentnodekeys.B+treesareusedtostoredatainfilesystems.B+treesrequirefewerI/Ooperationstosearchforanodeinthetree.Fan-outisdefinedasthenumberofnodespointingtothechildnodesofanodeinaB+tree.B+treeswerefirst describedinatechnicalpaperby RudolfBayerandEdwardM.McCreight.Theblock-orientedstoragecontextinB+treeshelpswiththestorageandefficientretrievalofdata.Thespaceefficiencyofa B+treecanbeenhancedbyusingcompressiontechniques.B+treesbelongtoafamilyofmultiwaysearchtrees.Forab-orderB+tree,spaceusageisoftheorderO(n).Inserting,finding,andremovingoperationsareoftheorderO(logbn).
![Page 253: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/253.jpg)
B-treeTheB-treeisasearchtreewithnon-leafnodesthatonly havekeys,andthedataisintheleaves.B-treesareusedtoreducethenumberofdiskaccesses.TheB-treeisaself-adjustingdatastructurethatkeepsdatasorted.B-treesstorekeysinasortedorderforeasytraversal.Theycanhandlemultiple insertionsanddeletions.Knuthinitiallycameupwiththeconceptofthisdatastructure.B-treesconsistofnodesthathaveatmostnchildren.Everynon-leafnodeinthetreehasatleastn/2childnodes. RudolfBayerandEdwardM.McCreightwerethefirsttoimplementthisdatastructureintheirwork.B-treesareusedinHFSandReiser4filesystemstoallowforquickaccesstoanyblockinafile.Onaverage,spaceusageisintheorderofO(n).Insert,search,anddeleteoperationsareintheorderofO(logn).
![Page 254: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/254.jpg)
T-treeTheT-treeisabalanceddatastructurethathasboththeindexandactualdatainmemory.Theyareusedinin-memorydatabases.Treferstotheshapeofthenode.Eachnodeconsistsofpointerstotheparentnodeandtheleftandrightchildnodes.Eachnodeinthetreenodewillhaveanorderedarrayofdatapointersandextracontroldata.T-treeshavesimilarperformancebenefitstoin-memorytreestructures.AT-treeisimplementedontopofaself-balancingbinarysearchtree.Thisdatastructureisgoodfororderedscanningofdata.Itsupportsvariousdegreesofisolation.
![Page 255: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/255.jpg)
TablesAswealreadyknow,tablesareusedindatamanagementandotherareas. Atablehasanameandaheaderwiththecolumnnames. Let'stakealookatthedifferentclassesintablessuchasthe Tableclass,theRowclass,theColumnclass,andthePrintTablemethodinthefollowingsections.Forthissection,pleaserefertothe table.gofile.
![Page 256: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/256.jpg)
TheTableclassATableclasshasanarrayofrowsandcolumnnames.Thetable'sNameisastring propertyinthestruct class,asshownhere:
//TableClasstypeTablestruct{Rows[]RowNamestringColumnNames[]string}
![Page 257: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/257.jpg)
TheRowclassTheRowclasshasanarrayofcolumnsandan Id integer,asshowninthefollowingcode.TheIdinstanceisauniqueidentifierforarow:
//RowClasstypeRowstruct{Columns[]ColumnIdint}
![Page 258: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/258.jpg)
TheColumnclassAColumnclasshasanIdinteger andaValue string that'sidentifiedbyauniqueidentifier,aspresentedinthefollowingcodesnippet:
//ColumnClasstypeColumnstruct{IdintValuestring}
![Page 259: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/259.jpg)
TheprintTablemethod
Inthefollowingcodesnippet,theprintTablemethodprintstherowsandcolumnsofatable.Rowsaretraversed,andthenforeveryrowthecolumnsareprinted:
//printTablefuncprintTable(tableTable){varrows[]Row=table.Rowsfmt.Println(table.Name)for_,row:=rangerows{varcolumns[]Column=row.Columnsfori,column:=rangecolumns{fmt.Println(table.ColumnNames[i],column.Id,column.Value);}}}
![Page 260: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/260.jpg)
Themainmethod
Inthismainmethod,wewillinstantiate theclassessuchasTable,Row,and Column,whichwejusttookalookat.Themainmethodcreatesatableandsetsthenameandcolumnnames.Columnsarecreatedwithvalues.Thecolumnsaresetontherowsaftertherowsarecreated. ThetableisprintedbyinvokingtheprintTablemethod,asshownhere:
//mainmethodfuncmain(){vartableTable=Table{}table.Name="Customer"table.ColumnNames=[]string{"Id","Name","SSN"}varrows[]Row=make([]Row,2)rows[0]=Row{}varcolumns1[]Column=make([]Column,3)columns1[0]=Column{1,"323"}columns1[1]=Column{1,"JohnSmith"}columns1[2]=Column{1,"3453223"}rows[0].Columns=columns1rows[1]=Row{}varcolumns2[]Column=make([]Column,3)columns2[0]=Column{2,"223"}columns2[1]=Column{2,"CurranSmith"}columns2[2]=Column{2,"3223211"}rows[1].Columns=columns2table.Rows=rowsfmt.Println(table)printTable(table)}
Runthefollowingcommandtoexecutethetable.gofile:goruntable.go
Theoutputisasfollows:
Thenextsectiontalksaboutthesymboltabledatastructure.
![Page 261: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/261.jpg)
SymboltablesAsymboltableispresentinmemoryduringtheprogramtranslationprocess.Itcanbepresentinprogrambinaries.Asymboltablecontainsthesymbol'sname,location,andaddress.InGo,thegosympackage implementsaccesstotheGosymbolandlinenumbertables.GobinariesgeneratedbytheGCcompilershavethesymbolandlinenumbertables.Alinetableisadatastructurethatmapsprogramcounterstolinenumbers.
![Page 262: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/262.jpg)
ContainersThecontainerspackageprovidesaccesstotheheap,list,andringfunctionalitiesinGo.Containersareusedinsocialnetworks,knowledgegraphs,andotherareas.Containersarelists,maps,slices,channels,heaps,queues,andtreaps. ListswereintroducedinChapter1,DataStructuresandAlgorithms.Mapsandslicesarebuilt-incontainersinGo.ChannelsinGoarecalledqueues.Aheapisatreedatastructure.Thisdatastructuresatisfiestheheapproperty.AqueueismodeledasaheapinChapter3,LinearDataStructures.Atreapisamixofatreeandaheap.Itisabinarytreewithkeysandvaluesandaheapthatmaintainspriorities.Aringiscalledacircularlinkedlistandispresentedinthenextsection. Forthissection,pleaserefertothecircular_list.gofile.
![Page 263: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/263.jpg)
CircularlinkedlistAcircularlinkedlistisadatastructureinwhichthelastnodeisfollowedbythefirstnode.Thecontainer/ringstructuresareusedtomodelcircularlinkedlists.Anexampleimplementationofacircularlinkedlistisshownasfollows:
packagemainimport("container/ring""fmt")funcmain(){varintegers[]intintegers=[]int{1,3,5,7}varcircular_list*ring.Ringcircular_list=ring.New(len(integers))variintfori=0;i<circular_list.Len();i++{circular_list.Value=integers[i]circular_list=circular_list.Next()}
Thering.Newmethodwiththelennasaparametercreatesacircularlistoflengthn.Thecircularlinkedlistisinitializedwithanintegerarraybymovingthrough circular_listwiththeNextmethod.TheDomethodofring.Ringclasstakestheelementasaninterface,andtheelementisprintedasfollows:
circular_list.Do(func(elementinterface{}){fmt.Print(element,",")})fmt.Println()
ThereverseofthecircularlististraversedusingthePrevmethod,andthevalueisprintedinthefollowingcode:
//reverseofthecircularlistfori=0;i<circular_list.Len();i++{fmt.Print(circular_list.Value,",")circular_list=circular_list.Prev()}fmt.Println()
Inthefollowingcodesnippet,thecircularlistismovedtwoelementsforwardusingtheMovemethod,andthevalueisprinted:
//movetwoelementsforwardinthecircularlistcircular_list=circular_list.Move(2)circular_list.Do(func(elementinterface{}){fmt.Print(element,",")})
![Page 264: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/264.jpg)
})
fmt.Println()}
Runthefollowingcommandtoexecutethe circular_list.gofile:goruncircular_list.go
Theoutputisasfollows:
Thenextsectiontalksaboutthehashfunctiondatastructure.
![Page 265: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/265.jpg)
ThehashfunctionsHashfunctionsareusedincryptographyandotherareas.Thesedatastructuresarepresentedwithcodeexamplesrelatedtocryptography.Therearetwowaystoimplementahash functioninGo:withcrc32orsha256.Marshaling(changingthestringtoanencodedform)savestheinternalstate,whichisusedforotherpurposeslater.ABinaryMarshaler (convertingthestringintobinaryform)exampleisexplainedinthissection:
//mainpackagehasexamplesshown//inHands-OnDataStructuresandalgorithmswithGobookpackagemain//importingbytes,crpto/sha256,encoding,fmtandlogpackageimport("bytes""crypto/sha256""encoding""fmt""log""hash")
Themainmethodcreatesabinarymarshaledhashoftwoexamplestrings.Thehashesofthetwostringsareprinted.Thesumofthefirsthashiscomparedwiththesecondhashusingtheequalsmethod onbytes.Thisisshowninthefollowingcode:
//mainmethodfuncmain(){const(example1="thisisaexample"example2="secondexample")varfirstHashhash.HashfirstHash=sha256.New()firstHash.Write([]byte(example1))varmarshalerencoding.BinaryMarshalervarokboolmarshaler,ok=firstHash.(encoding.BinaryMarshaler)if!ok{log.Fatal("firstHashisnotgeneratedbyencoding.BinaryMarshaler")}vardata[]bytevarerrerrordata,err=marshaler.MarshalBinary()iferr!=nil{log.Fatal("failuretocreatefirstHash:",err)}varsecondHashhash.HashsecondHash=sha256.New()varunmarshalerencoding.BinaryUnmarshalerunmarshaler,ok=secondHash.(encoding.BinaryUnmarshaler)
![Page 266: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/266.jpg)
unmarshaler,ok=secondHash.(encoding.BinaryUnmarshaler)
if!ok{log.Fatal("secondHashisnotgeneratedbyencoding.BinaryUnmarshaler")}iferr:=unmarshaler.UnmarshalBinary(data);err!=nil{log.Fatal("failuretocreatehash:",err)}firstHash.Write([]byte(example2))secondHash.Write([]byte(example2))fmt.Printf("%x\n",firstHash.Sum(nil))fmt.Println(bytes.Equal(firstHash.Sum(nil),secondHash.Sum(nil)))}
Runthefollowingcommandtoexecutethehash.gofile:gorunhash.go
Theoutputisasfollows:
![Page 267: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/267.jpg)
SummaryThischaptercoveredtrees,binarysearchtrees,andAVLtrees.Treap,B-trees,andB+treeswereexplainedbriefly.Operationssuchasinsertion,deletion,andupdatingelementsintreeswereshownwithvariouscodeexamples.Tables,containers,andhashfunctionswerepresentedinthelastsection.Thecomplexityintimeandspaceforoperationssuchasinsertion,deletion,andsearchwereexplainedineachsection.Inthenextchapter,homogeneousdatastructuressuchastwo-dimensionalandmulti-dimensionalarrayswillbecovered.
![Page 268: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/268.jpg)
Questions1. Canyougiveanexamplewhereyoucanuseabinarysearchtree?2. Whichmethodisusedtosearchforanelementinabinarysearchtree?3. WhichtechniquesareusedtoadjustthebalanceinanAVLtree?4. Whatisasymboltable?
1. Whichclassandmethodarecalledtogenerateabinarymarshaledhashonthehashclass?
2. WhichcontainerinGoisusedtomodelacircularlinkedlist?3. HowdoyoucreateaJSON(indented)fromatreestructure?Whichclassandmethodareused?
4. Howdoyoucomparethesumofhashes?5. WhatisthebalancefactorinanAVLtree?6. Howdoyouidentifyarowandcolumninatable?
![Page 269: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/269.jpg)
Furtherreading
Thefollowingbooksarerecommendedifyouwanttoknowmoreabouttrees,binarysearchtrees,andAVLtrees:
DesignPatterns, byErichGamma,RichardHelm,RalphJohnson,andJohnVlissidesIntroductiontoAlgorithms –ThirdEdition,byThomasH.Cormen,CharlesE.Leiserson,RonaldL.Rivest,andCliffordSteinDatastructuresandAlgorithms:AnEasyIntroduction,by RudolphRussell
![Page 270: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/270.jpg)
HomogeneousDataStructuresHomogeneousdatastructurescontainsimilartypesofdata,suchasintegersordoublevalues.Homogeneousdatastructuresareusedinmatrices,aswellastensorandvectormathematics. Tensorsaremathematicalstructuresforscalarsandvectors. Afirst-ranktensorisavector.Avectorconsistsofaroworacolumn.Atensorwithzerorankisascalar. Amatrixisatwo-dimensionalclusterofnumbers. Theyareallusedinscientificanalysis.Tensorsareusedinmaterialscience.Theyareusedinmathematics,physics,mechanics,electrodynamics,andgeneralrelativity.Machinelearningsolutionsutilizeatensordatastructure.Atensorhaspropertiessuchasposition,shape,andastaticsize.Thischaptercoversthefollowinghomogeneousdatastructures:
Two-dimensional arraysMulti-dimensionalarrays
Thefollowingscenariosareshowntodemonstratetheusageoftwo-dimensionalandmulti-dimensionalarrays:
MatrixrepresentationMultiplicationAdditionSubtractionDeterminantcalculationInversionTransposition
![Page 271: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/271.jpg)
TechnicalrequirementsInstallGoVersion1.10from https://golang.org/doc/install foryourOS.TheGitHubURLforthecodeinthischapterisasfollows: https://github.com/PacktPublishing/Learn-Data-Structures-and-Algorithms-with-Golang/tree/master/Chapter05.
![Page 272: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/272.jpg)
Two-dimensionalarraysTwo-dimensionalarrayswerepresentedbrieflyinChapter2,GettingStartedwithGoforDataStructuresandAlgorithms.Torecap,fordynamicallocation,weusesliceofslices,whichisatwo-dimensionalarray.Atwo-dimensionalarray,is alistof single-dimensionalarrays.Everyelementinatwo-dimensionalarrayarr,isidentifiedasarr[i][j],wherearristhenameofthearrayandiandjrepresentrowsandcolumns,andtheirvaluesrangingfrom0tomand0ton,respectively.Traversingatwo-dimensionalarrayisofO(m*n)complexity.Thefollowingcodeshowshowtoinitializeanarray:
vararr=[4][5]int{
{4,5,7,8,9},
{1,2,4,5,6},
{9,10,11,12,14},
{3,5,6,8,9}}
Anelementinatwo-dimensionalarrayisaccessedwitharowindexandcolumnindex.Inthefollowingexample,thearray'svalueinrow2andcolumn3isretrievedasanintegervalue:
varvalueint=arr[2][3]
Arrayscanstoreasequentialcollectionofdataelementsofthesametype.Homogeneousdatastructurearraysconsistofcontiguousmemoryaddresslocations.Two-dimensionalmatricesaremodeledastwo-dimensionalarrays.Ascalarisanelementofafieldthatdefinesavectorspace.Amatrixcanbemultipliedbyascalar.Youcandivideamatrixbyanynon-zerorealnumber.Theorderofamatrixisthenumberofrows, m,bythenumberofcolumns, n.Amatrixwithrowsmandcolumnsnisreferredtoasanmxnmatrix.Thereare multipletypes of matrices,suchasarowmatrix,
![Page 273: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/273.jpg)
nmatrix.Thereare multipletypes of matrices,suchasarowmatrix,
columnmatrix,triangularmatrix,nullmatrix,andzeromatrix; let'sdiscusstheminthefollowingsections.
![Page 274: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/274.jpg)
RowmatrixArowmatrixisa1xmmatrixconsistingofasinglerowofmelements,asshownhere:
varmatrix=[1][3]int{{1,2,3}}
Runthefollowingcommandtoexecutetherow_matrix.gofile:gorunrow_matrix.go
Theoutputisasfollows:
Thenextsectiontalksaboutthecolumnmatrixdatastructure.
![Page 275: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/275.jpg)
ColumnmatrixAcolumnmatrixisanmx1matrixthathasasinglecolumnofmelements.Thefollowingcodesnippetshowshowtocreateacolumnmatrix:
varmatrix=[4][1]int{{1},{2},{3},{4}}
Runthefollowingcommandtoexecutethecolumn_matrix.gofile:goruncolumn_matrix.go
Theoutputisasfollows:
Thenextsectiontalksaboutthelowertriangularmatrixdatastructure.
![Page 276: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/276.jpg)
LowertriangularmatrixAlowertriangularmatrixconsistsofelementsthathaveavalueofzeroabovethemaindiagonal.Thefollowingcodesnippetshowshowto createalowertriangularmatrix:
varmatrix=[3][3]int{{1,0,0},{1,1,0},{2,1,1}}
Runthefollowingcommandtoexecutethelower_triangular.gofile:gorunlower_triangular.go
Theoutputisasfollows:
Thenextsectiontalksabouttheuppertriangularmatrixdatastructure.
![Page 277: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/277.jpg)
UppertriangularmatrixAnuppertriangularmatrixconsistsofelementswithavalueofzerobelowthemaindiagonal.Thefollowingcodecreatesanuppertriangularmatrix:
varmatrix=[3][3]int{{1,2,3},{0,1,4},{0,0,1}}
Runthefollowingcommandtoexecutetheupper_triangular.gofile:gorunupper_triangular.go
Theoutputisasfollows:
Thenextsectiontalksaboutthe nullmatrixdatastructure.
![Page 278: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/278.jpg)
NullmatrixAnullorazeromatrixisamatrixentirelyconsistingofzerovalues,asshowninthefollowingcodesnippet:
varmatrix=[3][3]int{{0,0,0},{0,0,0},{0,0,0}}
Runthefollowingcommandtoexecutethenull_matrix.gofile:gorunnull_matrix.go
Theoutputisasfollows:
Thenextsectiontalksabouttheidentitymatrixdatastructure.
![Page 279: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/279.jpg)
IdentitymatrixAnidentitymatrixisaunitmatrixwithonesareonthemaindiagonalandzerosareelsewhere. Thefollowingcodesnippetcreatesanidentitymatrix:
///mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain
//importingfmtpackage
import(
"fmt")//identitymethod
funcIdentity(orderint)[][]float64{
varmatrix[][]float64matrix=make([][]float64,order)
variint
fori=0;i<order;i++{
vartemp[]float64temp=make([]
![Page 280: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/280.jpg)
float64,order)temp[i]=1matrix[i]=temp
}
returnmatrix
}
//mainmethod
funcmain(){fmt.Println(Identity(4))
}
Runthefollowingcommandtoexecutetheprecedingcodesnippet:gorunidentity_matrix.go
Theoutputisasfollows:
Thenextsectiontalksaboutthesymmetricmatrixdatastructure.
![Page 281: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/281.jpg)
SymmetricmatrixAsymmetricmatrixisamatrixwhosetransposeisequaltoitself.Symmetricmatricesincludeothertypesofmatricessuchasantimetric,centrosymmetric,circulant,covariance,coxeter,hankel,hilbert,persymmetric,skew-symmetric,andtoeplitzmatrices.Anegativematrixisamatrixinwhicheachelementisanegativenumber.
![Page 282: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/282.jpg)
Basic2DmatrixoperationsInthissection,wewilllookatthebasicoperationsonthetwo-dimensionalmatrix.Let'sstartwithinitializingthematrices.matrix1andmatrix2areinitializedinthefollowingcodesnippet:
varmatrix1=[2][2]int{
{4,5},
{1,2}
}
varmatrix2=[2][2]int{
{6,7},
{3,4}
}
Theadd,subtract,multiply,transpose,andinversionoperations arepresentedinthenextfewsections. Forthissection,pleaserefertothe binary_search_tree.go file.
![Page 283: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/283.jpg)
Theaddmethod
Theaddmethodaddstheelementsoftwo2x2matrices.Thefollowingcodereturnsthecreatedmatrixbyaddingthetwomatrices:
//addmethod
funcadd(matrix1[2][2]int,matrix2[2][2]int)[2][2]int{
varmint
varlint
varsum[2][2]int
forl=0;l<2;l++{
form=0;m<2;m++{
sum[l][m]=matrix1[l][m]+matrix2[l][m]
}
}
returnsum
}
Thesumbetweenthetwomatricesistheresultofcallingthe add method.Theparametersthatarepassedarethematricestobeadded,asshownhere:
varsum[2][2]int
sum=add(matrix1,matrix2)
Theexampleoutputoftheaddmethodisasfollows.Addingmatrix1andmatrix2givesasummatrix:
![Page 284: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/284.jpg)
![Page 285: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/285.jpg)
Thesubtractmethod
Thesubtractmethodsubtractstheelementsoftwo2x2matrices.Thesubtractmethodinthefollowingsnippetsubtractstheelementsofmatrix1andmatrix2.Thismethodreturnstheresultingmatrixaftersubtraction:
//subtractmethod
funcsubtract(matrix1[2][2]int,matrix2[2][2]int)[2][2]int{
varmint
varlint
vardifference[2][2]int
forl=0;l<2;l++{
form=0;m<2;m++{
difference[l][m]=matrix1[l][m]-matrix2[l][m]
}
}
returndifference
}
Thedifferencebetweentwomatricesistheresultofcallingthesubtractmethod.Theparametersthatare passedarethematricestobesubtracted,asshownhere:
vardifference[2][2]int
difference=subtract(matrix1,matrix2)
Theexampleoutputofthesubtractmethodisasfollows:
![Page 286: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/286.jpg)
![Page 287: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/287.jpg)
Themultiplymethod
Themultiplymethodmultipliestheelementsoftwo2x2matrices.Themultiplicationoftwomatrices,matrix1andmatrix2,isshowninthefollowingsnippet.Thematrixthat's generated afterthemultiplicationisreturnedbythemultiplymethod:
//multiplymethodfuncmultiply(matrix1[2][2]int,matrix2[2][2]int)[2][2]int{varmintvarlintvarnintvarproduct[2][2]intforl=0;l<2;l++{form=0;m<2;m++{varproductSumint=0forn=0;n<2;n++{productSum=productSum+matrix1[l][n]*matrix2[n][m]}product[l][m]=productSum;}}returnproduct}
Theproductoftwomatricesiscalculatedusingthemultiplymethodinthefollowingcodesnippet,whichtakesthetwomatricesasparameters:
varproduct[2][2]int
product=multiply(matrix1,matrix2)
Theexampleoutputofthemultiplymethodisasfollows.Theproductofmatrix1andmatrix2istheproductmatrix:
![Page 288: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/288.jpg)
Thetransposemethod
Thetransposeofamatrixisachievedusingthetransposemethod.Thismethodtakesthematrixasaparameterandreturnsthetransposedmatrix:
//transposemethod
functranspose(matrix1[2][2]int)[2][2]int{varmintvarlintvartransMatrix[2][2]intforl=0;l<2;l++{form=0;m<2;m++{
transMatrix[l][m]=matrix1[m][l]
}}returntransMatrix}
![Page 289: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/289.jpg)
Thedeterminantmethod
Thedeterminantmethodcalculatesthedeterminantofthematrix.Thedeterminantmethodinthefollowingcodesnippetcalculatesthedeterminantvalueofamatrix.Themethodtakesthematrixandreturnsafloat32value,whichisthedeterminantofthematrix:
//determinantmethodfuncdeterminant(matrix1[2][2]int)float32{
varmint
varlint
vardetfloat32
det=det+((matrix1[0][0]*matrix1[1][1])-(matrix1[0][1]*matrix1[1][0]));
returndet
}
![Page 290: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/290.jpg)
Theinversemethod
Theinversemethodreturnstheinverseofthematrix,whichispassedasaparameter.Thisisshowninthefollowingsnippet:
//inversemethod
funcinverse(matrix[2][2]int)[][]float64{
vardetfloat64
det=determinant(matrix)
varinvmatrixfloat64
invmatrix[0][0]=matrix[1][1]/det
invmatrix[0][1]=-1*matrix[0][1]/det
invmatrix[1][0]=-1*matrix[1][0]/det
invmatrix[1][1]=matrix[0][0]/det
returninvmatrix
}
Runthefollowingcommandtoexecutethetwodmatrix.gofile:goruntwodmatrix.go
Theoutputisasfollows:
![Page 291: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/291.jpg)
Thenextsectiontalksaboutthezig-zagmatrixdatastructure.
![Page 292: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/292.jpg)
Zig-zagmatrixAzig-zagmatrixisasquarearrangementofn x nintegers.Theintegersarearrangedonanti-diagonalsinsequentiallyincreasingorder.Thefollowingcodeexplainshowtocreateazig-zagmatrixandalsohowtotraverseit.The PrintZigZagmethodcreatesthematrixinazig-zagfashionwiththeelementsinasequentiallyincreasingorder.Themethodtakestheintegernasaparameterandreturnstheintegerarray,whichisthezig-zagmatrix:
///mainpackagehasexamplesshown
//inGoDataStructuresandalgorithmsbook
packagemain
//importingfmtpackage
import(
"fmt"
)
//printsthematrixinzig-zagfashion
funcPrintZigZag(nint)[]int{
varzigzag[]int
zigzag=make([]int,n*n)
variint
![Page 293: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/293.jpg)
i=0
varmint
m=n*2
varpint
forp=1;p<=m;p++{
varxint
x=p-n
ifx<0{
x=0
}
varyint
y=p-1
ify>n-1{
![Page 294: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/294.jpg)
y=n-1
}
varjint
j=m-p
ifj>p{
j=p
}
varkint
fork=0;k<j;k++{
ifp&1==0{
zigzag[(x+k)*n+y-k]=i
}else{
zigzag[(y-k)*n+x+k]=i
}
![Page 295: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/295.jpg)
}
i++
}
}
returnzigzag
}
ThemainmethodinvokesthePrintZigZagmethod,whichtakestheparameternandprintsthematrixfirst fromlefttoright,thenfromrighttoleftforthesecondlevel,andsoon.Thenumberofintegersis5andthefieldwidthis2:
//mainmethod
funcmain(){
varnintn=5
varlengthint
length=2
variint
varsketchint
![Page 296: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/296.jpg)
varsketchint
fori,sketch=rangePrintZigZag(n){
fmt.Printf("%*d",length,sketch)
ifi%n==n-1{
fmt.Println("")
}
}
}
Runthefollowingcommandtoexecutethezigzagmatrix.gofile:gorunzigzagmatrix.go
Theoutputisasfollows:
![Page 297: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/297.jpg)
Thenextsectiontalksaboutthe spiralmatrixdatastructure.
![Page 298: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/298.jpg)
SpiralmatrixAspiralmatrixisanarrangementofn x nintegersinwhichintegersarearrangedspirallyinsequentiallyincreasingorder.Aspiralmatrixisanoldtoyalgorithm.Thespiralorderismaintainedusingfourloops,one foreachcornerofthematrix.The PrintSpiralmethodinthefollowingcodesnippetcreatesamatrixwithelements arrangedspirallyinincreasingorder.Themethodtakesaparameter,n,andreturnsanintegerarray:
///mainpackagehasexamplesshown
//inGoDataStructuresandalgorithmsbook
packagemain
//importingfmtpackage
import(
"fmt"
)
//PrintSpiralmethodfuncPrintSpiral(nint)[]int{
varleftintvartopintvarrightintvarbottomint
left=0top=0right=n-1bottom=n-1varsizeintsize=n*nvars[]ints=make([]int,size)
![Page 299: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/299.jpg)
variinti=0forleft<right{
varcintforc=left;c<=right;c++{s[top*n+c]=ii++}top++
varrintforr=top;r<=bottom;r++{s[r*n+right]=ii++}right--iftop==bottom{break}
forc=right;c>=left;c--{s[bottom*n+c]=ii++}bottom--
forr=bottom;r>=top;r--{s[r*n+left]=ii++}left++}
s[top*n+left]=i
returns}
Inthefollowingcodesnippet, themainmethodinvokesthePrintSpiralmethod,whichtakestheintegernandprintstheintegervaluesofthematrix spirally.ThevaluesreturnedfromthePrintSpiralmethodareprintedasfieldswithawidthof2:
funcmain(){varnintn=5varlengthintlength=2
![Page 300: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/300.jpg)
length=2
variintvarsketchintfori,sketch=rangePrintSpiral(n){fmt.Printf("%*d",length,sketch)ifi%n==n-1{fmt.Println("")}}}
Runthefollowingcommandtoexecutethespiralmatrix.gofile:gorunspiralmatrix.go
Theoutputisasfollows:
ThenextsectiontalksabouttheBooleanmatrixdatastructure.
![Page 301: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/301.jpg)
BooleanmatrixABooleanmatrixisamatrix thatconsistsofelementsinthemth rowandthenth columnwithavalueof1. AmatrixcanbemodifiedtobeaBooleanmatrixbymakingthevaluesinthe mth rowandthe nth columnequalto1.Inthefollowingcode,theBooleanmatrixtransformationandprintmethodsareshownindetail.ThechangeMatrixmethodtransformstheinputmatrixintoaBooleanmatrixbychangingtherowandcolumnvaluesfrom0to1ifthecellvalueis1.Themethodtakestheinputmatrixastheparameterandreturnsthechangedmatrix,asshowninthefollowingcode:
///mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain
//importingfmtpackageimport("fmt")//changeMatrixmethodfuncchangeMatrix(matrix[3][3]int)[3][3]int{variintvarjintvarRows[3]intvarColumns[3]int
varmatrixChanged[3][3]int
fori=0;i<3;i++{forj=0;j<3;j++{ifmatrix[i][j]==1{Rows[i]=1Columns[j]=1}
}}
fori=0;i<3;i++{forj=0;j<3;j++{ifRows[i]==1||Columns[j]==1{matrixChanged[i][j]=1}
}
![Page 302: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/302.jpg)
}
}
returnmatrixChanged
}
Theexampleoutputofthechangematrixmethodisshownthefollowingscreenshot.Theelementswith1intheroworcolumnarecheckedandtherowelementsareupdatedto1:
Let'stakealookattheprintMatrixmethodandthemainmethod.
![Page 303: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/303.jpg)
TheprintMatrix method
Inthefollowingcodesnippet, the printMatrixmethodtakestheinputmatrixandprintsthematrixvaluesbyrowandtraversesthecolumnsforeveryrow:
//printMatrixmethodfuncprintMatrix(matrix[3][3]int){variintvarjint//varkintfori=0;i<3;i++{
forj=0;j<3;j++{
fmt.Printf("%d",matrix[i][j])
}fmt.Printf("\n")}
}
![Page 304: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/304.jpg)
Themainmethod
ThemainmethodinthefollowingcodesnippetinvokesthechangeMatrix methodafterinitializingthematrix.Thechanged matrixisprintedaftertheinvocationofthechangeMatrixmethod:
//mainmethodfuncmain(){
varmatrix=[3][3]int{{1,0,0},{0,0,0},{0,0,0}}
printMatrix(matrix)
matrix=changeMatrix(matrix)
printMatrix(matrix)
}
Runthefollowingcommandtoexecutetheboolean_matrix.gofile:gorunboolean_matrix.go
Theoutputisasfollows:
![Page 305: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/305.jpg)
Thenextsectiontalksaboutmulti-dimensionalarrays.
![Page 306: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/306.jpg)
Multi-dimensionalarraysAnarrayisahomogeneouscollectionofdataelements.Anarray'sindexesrangefromindex0toindexm-1,wheremisthefixedlengthofthearray.Anarraywithmultipledimensionsisanarrayofanarray.Thefollowingcodeinitializesamulti-dimensionalarray. Athree-dimensionalarrayisprinted:
///mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain
//importingfmtpackageimport("fmt""math/rand")//mainmethodfuncmain(){
varthreedarray[2][2][2]int
variint
varjint
varkint
fori=0;i<2;i++{
forj=0;j<2;j++{
fork=0;k<2;k++{
threedarray[i][j][k]=rand.Intn(3)}}}
fmt.Println(threedarray)}
![Page 307: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/307.jpg)
Runthefollowingcommandtoexecutetheprecedingcodesnippet:gorunmultidarray.go
Theoutputisasfollows:
Thenextsectiontalksabouttensordatastructures.
![Page 308: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/308.jpg)
TensorsAtensorisamulti-dimensionalarrayofcomponentsthatarespatialcoordinates.Tensorsareusedextensively inphysicsandbiologicalstudiesintopicssuchaselectromagnetismanddiffusiontensorimaging.WilliamRowanHamiltonwasthefirsttocomeupwiththetermtensor.Tensorsplayabasicroleinabstractalgebraandalgebraictopology.Thetensororderisthesumoftheorderofitsarguments,plustheorderoftheresulttensor.Forexample,aninertiamatrixisasecond-ordertensor.Spinorsarealsomulti-dimensionalarrays,butthevaluesoftheirelementschangeviacoordinatetransformations.Theinitializationofatensorisshownhere.Thearrayisinitializedwithintegervaluesrangingfrom0to3:
vararray[3][3][3]intvariintvarjintvarkintfori=0;i<3;i++{forj=0;j<3;j++{fork=0;k<3;k++{
array[i][j][k]=rand.Intn(3)}}}
Unfoldingatensorisdonealongthefirstdimension.Rearrangingthetensormode'snvectorsisreferredtoasmoden-unfoldingofatensor.0-modeunfoldingofatensorarrayisshownhere:
forj=0;j<3;j++{fork=0;k<3;k++{fmt.Printf("%d",array[0][j][k])}fmt.Printf("\n")}
1-modeunfoldingofatensorarrayisshownhere.Thearray'sfirstdimensionindexissetto1:
forj=0;j<3;j++{fork=0;k<3;k++{fmt.Printf("%d",array[1][j][k])}fmt.Printf("\n")
![Page 309: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/309.jpg)
fmt.Printf("\n")
}
The2-modeunfoldingofatensorarrayisshownhere.Thearray'sfirstdimensionrowindexissetto2:
forj=0;j<3;j++{fork=0;k<3;k++{fmt.Printf("%d",array[2][j][k])}fmt.Printf("\n")}
Runthefollowingcommandtoexecutethetensor.gofile:goruntensor.go
Theoutputisasfollows:
![Page 310: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/310.jpg)
![Page 311: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/311.jpg)
SummaryThischaptercoveredhomogeneousdatastructuressuchastwo-dimensionalarraysandmulti-dimensionalarrays.Matrixoperationssuchassum,subtraction,multiplication,inverse, anddeterminanthavebeenexplainedwithcodeexamples.Spiralmatrices,zig-zagmatrices,andBooleanmatriceshavebeenexplainedusingtwo-dimensionalarrays.Tensorsandoperationssuchasfoldingwerealsocovered.Inthenextchapter,heterogeneousdatastructuressuchaslinkedlists,orderedlists,andunorderedlistswillbecovered.
![Page 312: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/312.jpg)
Questions1. Whatis2-modeunfoldingofatensorarray?2. Writeatwo-dimensionalarrayofstringsandinitializeit.Printthestrings.3. Giveanexampleofamulti-dimensionalarrayandtraversethroughit.4. Fora3x3matrix,writecodethatcalculatesthedeterminantofthematrix.
5. Whatisatransposeofa3x3matrix?6. Whatisazig-zagmatrix?7. Writecodewithanexampleofaspiralmatrix.8. Whichdimensionistypicallyunfoldedfortensorarrays?9. HowdoyoudefineaBooleanmatrix?10. Choosetwo3x3matricesandfindtheproductofthematrices.
![Page 313: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/313.jpg)
Furtherreading
Thefollowingbooksarerecommendedifyouwanttolearnmoreaboutarrays,matrices,andtensors:
AdvancedDataStructures,by PeterBrassDynamicDataStructures:Lists,Stacks,Queues,andTrees, byBogdanPatrut,andTiberiuSocaciuDatastructuresandAlgorithms:AnEasyIntroduction,by RudolphRussell
![Page 314: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/314.jpg)
HeterogeneousDataStructuresHeterogeneousdatastructuresaredatastructuresthatcontaindiversetypesofdata,suchasintegers,doubles,andfloats.Linkedlistsandorderedlistsaregoodexamplesofthesedatastructures.Theyareusedformemorymanagement.Alinkedlistisachainofelementsthatareassociatedtogetherbymeansofpointers.Eachelement'spointerlinkstothefollowingitem,whichconnectsthechaintogether.Linkedlistsdon'thavetotakeupablockofmemory.Thememorythattheyutilizecanbeallocateddynamically.Itcomprisesaprogressionofnodes,whicharethecomponentsofthelist.OrderedlistsandunorderedlistsfromHTMLareshowntodemonstratetheusageoflistsandstoragemanagement.Wewillcoverlinkedlists,orderedlists,andunorderedlistsinthischapterandshowtheimplementationoftheirmethodswithappropriateexamples.Thischaptercoversthefollowingheterogeneousdatastructures:
LinkedlistsOrderedlistsUnorderedlists
WecoveredsinglylinkedlistsanddoublylinkedlistswithcodeexamplesinChapter3,LinearDataStructures.Circular-linkedlistswerecoveredinChapter4,Non-LinearDataStructures.
![Page 315: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/315.jpg)
TechnicalrequirementsInstallGoVersion1.10foryourOSfromthefollowinglink:https://golang.org/doc/install.TheGitHubURLforthecodeinthischapterisasfollows:https://github.com/PacktPublishing/Learn-Data-Structures-and-Algorithms-with-Golang/tree/master/Chapter06.
![Page 316: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/316.jpg)
LinkedlistsAlinkedlistisalinearcollectionofelementswithinformation.Thelinkedlistshrinksorexpandsbasedonwhetherthecomponentsaretobeincludedorremoved.Thislistcanbesmallorenormous,yet,regardlessofthesize,theelementsthatmakeituparestraightforward.LinkedlistswerecoveredinChapter3,LinearDataStructures.Theyconsumemorememorythanarrays.Reversetraversingisaproblemforsinglylinkedlistsbecauseasinglylinkedlistpointstothenextnodeforward.Thenextsectionexplainshowtoreverseasinglylinkedlistwithacodeexample.Singly,doubly,andcircular-linkedlistswillbecoveredinthischapter.
![Page 317: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/317.jpg)
SinglylinkedlistsAsinglylinkedlistisadynamicdatastructureinwhichadditionandremovaloperationsareeasy;thisisbecauseit'sadynamicdatastructureandnotfixed.Stackandqueuedatastructuresareimplementedwithlinkedlists.Morememoryisconsumedwhenelementsaredynamicallyaddedbecausedynamicdatastructuresaren'tfixed.Randomretrievalisnotpossiblewithasinglylinkedlistbecauseyouwillneedtotraversethenodesforapositionednode.Insertionintoasinglylinkedlistcanbeatthebeginningorendofthelist,andafteraspecifiednode.Deletioncanhappenatthebeginningorendofthelistandafteraspecifiednode.Reversingasinglylinkedlistisshowninthissection.Themethodsthatareexplainedinthissectionareapartofthelinked_list.gofilethat'sprovidedinthecodebundle.TheNodeclassisdefinedinthissnippetwithanodepointer,nextNode,andaruneproperty:
//mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain
//importingfmtpackageimport("fmt")
//NodestructtypeNodestruct{nextNode*Nodepropertyrune}
Themethodsofsinglylinkedlistsarediscussedinthefollowingsections.
![Page 318: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/318.jpg)
TheCreateLinkedListmethod
TheCreateLinkedListmethodcreatesalinkedlistofrunesfromatoz://createListmethodfuncCreateLinkedList()*Node{varheadNode*NodeheadNode=&Node{nil,'a'}varcurrNode*NodecurrNode=headNodevarirunefori='b';i<='z';i++{varnode*Nodenode=&Node{nil,i}currNode.nextNode=nodecurrNode=node}returnheadNode}
TheexampleoutputfortheCreateLinkedListmethodisshownasfollows.TheheadNodeiscreatedwithavalueof97.Thelinkedlistiscreatedwithnodesstartingfromatoz:
![Page 319: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/319.jpg)
TheReverseLinkedListmethod
TheReverseLinkedListfunctiontakesanodepointer,nodeList,andreturnsanodepointertoareversedlinkedlist.Thefollowingcodesnippetshowshowthelinkedlistisreversed:
//ReverseListmethodfuncReverseLinkedList(nodeList*Node)*Node{varcurrNode*NodecurrNode=nodeListvartopNode*Node=nilfor{ifcurrNode==nil{break}vartempNode*NodetempNode=currNode.nextNodecurrNode.nextNode=topNodetopNode=currNodecurrNode=tempNode}returntopNode}
Theexampleoutputforthereverselinkedlistmethodisasfollows.Themethodtakestheparameterofalinkedstringstartingfromatoz.Thereversedlistisfromztoanodes:
![Page 320: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/320.jpg)
Themainmethod
Themainmethodcreatesthelinkedlist,andprintsthelinkedlistandthereversedlistinstringformat:
//mainmethodfuncmain(){varlinkedList=CreateLinkedList()StringifyList(linkedList)StringifyList(ReverseLinkedList(linkedList))}
Runthefollowingcommandtoexecutethelinked_list.gofile:gorunlinked_list.go
Thisistheoutput:
Thenextsectiontalksaboutthedoublylinkedlistdatastructure.
![Page 321: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/321.jpg)
DoublylinkedlistsAdoublylinkedlistisadatastructurethatconsistsofnodesthathavelinkstothepreviousandthenextnodes.DoublylinkedlistswerepresentedwithcodeexamplesinChapter3,LinearDataStructures.ListsinGoareimplementedasdoublylinkedlists.Theelements14and1arepushedbackwardandforward,respectively.Theelements6and5areinsertedbeforeandafter.Thedoublylinkedlistisiteratedandtheelementsareprinted.Thecodeinthissectionshowshowlistscanbeused:
//mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain
//importingfmtandlistpackageimport("container/list""fmt")
//mainmethodfuncmain(){varlinkedList*list.ListlinkedList=list.New()varelement*list.Elementelement=linkedList.PushBack(14)varfrontElement*list.ElementfrontElement=linkedList.PushFront(1)linkedList.InsertBefore(6,element)linkedList.InsertAfter(5,frontElement)
varcurrElement*list.ElementforcurrElement=linkedList.Front();currElement!=nil;currElement=currElement.Next(){fmt.Println(currElement.Value)}}
Runthefollowingcommandtoexecutethedouble_linked_list.gofile:gorundouble_linked_list.go
Thisistheoutput:
![Page 322: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/322.jpg)
Thenextsectiontalksaboutthecircular-linkedlistdatastructure.
![Page 323: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/323.jpg)
Circular-linkedlistsAcircular-linkedlistisacollectionofnodesinwhichthelastnodeisconnectedtothefirstnode.Circular-linkedlistswerebrieflycoveredinChapter4,Non-LinearDataStructures.Circular-linkedlistsareusedtocreateacircularqueue.Inthefollowingsection,acircularqueuestructisdefinedandimplemented.Themethodsthatareexplainedinthissectionarepartofthecircular_queue.gofilegiveninthecodebundle.
![Page 324: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/324.jpg)
TheCircularQueueclassTheCircularQueueclasshassize,head,andlastintegerproperties,aswellasanodesarray.Theclassisdefinedinthefollowingcodesnippet:
//mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain
//importingfmtpackageimport("fmt")
//CircularQueuetypeCircularQueuestruct{sizeintnodes[]interface{}headintlastint}
Let'sdiscussthedifferentmethodsoftheCircularQueueclassinthefollowingsections.
![Page 325: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/325.jpg)
TheNewQueuemethod
TheNewQueuemethodcreatesanewinstanceofthecircularqueue.TheNewQueuefunctiontakesthenumparameter,whichisthesizeofthequeue.Thefunctionreturnsthecircularqueueofnodes,asshowninthefollowingcode:
//NewCircularQueuemethodfuncNewQueue(numint)*CircularQueue{varcircularQueueCircularQueuecircularQueue=CircularQueue{size:num+1,head:0,last:0}circularQueue.nodes=make([]interface{},circularQueue.size)return&circularQueue}
![Page 326: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/326.jpg)
TheIsUnUsedmethod
TheIsUnUsedmethodoftheCircularQueueclassinthefollowingsnippetcheckswhetherheadisequaltothelastnodeandreturnstrueifso;otherwise,itreturnsfalse:
//IsUnUsedmethodfunc(circularQueueCircularQueue)IsUnUsed()bool{returncircularQueue.head==circularQueue.last}
![Page 327: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/327.jpg)
TheIsCompletemethod
TheIsCompletefunctionoftheCircularQueueclassreturnstrueiftheheadnode'spositionisthesameasthelastnodeposition+1;otherwise,itreturnsfalse:
//IsCompletemethodfunc(circularQueueCircularQueue)IsComplete()bool{returncircularQueue.head==(circularQueue.last+1)%circularQueue.size}
![Page 328: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/328.jpg)
TheAddmethod
Thismethodaddsthegivenelementtothecircularqueue.Inthefollowingcodesnippet,theAddmethodtakesanelementparameteroftheinterfacetypeandaddstheelementtothecircularqueue:
//Addmethodfunc(circularQueue*CircularQueue)Add(elementinterface{}){ifcircularQueue.IsComplete(){panic("QueueisCompletelyUtilized")}circularQueue.nodes[circularQueue.last]=elementcircularQueue.last=(circularQueue.last+1)%circularQueue.size}
TheexampleoutputfortheAddmethodisasfollows.TheAddmethodtakestheelementwithvalue1andupdatesthequeue:
![Page 329: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/329.jpg)
TheMoveOneStepmethod
TheMoveOnestepmethodmovestheelementonestepforwardinthecircularqueue.TheMoveOneStepmethodtakestheelementparameteroftheinterfacetypeandmovestheheadnodetopositiontwoaftersettingtheelementastheheadnode:
//MoveOneStepmethodfunc(circularQueue*CircularQueue)MoveOneStep()(elementinterface{}){ifcircularQueue.IsUnUsed(){returnnil}element=circularQueue.nodes[circularQueue.head]circularQueue.head=(circularQueue.head+1)%circularQueue.sizereturn}
![Page 330: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/330.jpg)
Themainmethod
Themainmethodcreatesthequeueandaddselementstothecircularqueue:
//mainmethodfuncmain(){varcircularQueue*CircularQueuecircularQueue=NewQueue(5)circularQueue.Add(1)circularQueue.Add(2)circularQueue.Add(3)circularQueue.Add(4)circularQueue.Add(5)fmt.Println(circularQueue.nodes)
}
Runthefollowingcommandtoexecutethecircular_queue.gofile:goruncircular_queue.go
Thisistheoutput:
Inthefollowingsections,orderedlistsandunorderedlistsareexplainedwithcodeexamples.
![Page 331: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/331.jpg)
OrderedlistsListsinGocanbesortedintwoways:
Orderedlist:BycreatingagroupofmethodsfortheslicedatatypeandcallingsortUnorderedlist:Theotherwayistoinvokesort.Slicewithacustomlessfunction
Theonlydifferencebetweenanorderedlistandanunorderedlististhat,inanorderedlist,theorderinwhichtheitemsaredisplayedismandatory.AnorderedlistinHTMLstartswithan<ol>tag.Eachiteminthelistiswrittenin<li>tags.Here'sanexample:
<ol>
<li>Stones</li>
<li>Branches</li>
<li>Smoke</li>
</ol>
AnexampleofanorderedlistusingGolangisshowninthefollowingcodesnippet.TheEmployeeclasshasName,ID,SSN,andAgeproperties:
///mainpackagehasexamplesshown
//inGoDataStructuresandalgorithmsbook
packagemain
//importingfmtandsortpackage
import(
![Page 332: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/332.jpg)
"fmt"
"sort"
)
//classEmployee
typeEmployeestruct{
Namestring
IDstring
SSNint
Ageint
}
Themethodsthatareexplainedinthefollowingsectionsareapartofthelinked_list.gofilethat'sprovidedinthecodebundle.
![Page 333: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/333.jpg)
TheToStringmethod
TheToStringmethodoftheEmployeeclassreturnsastringversionofemployee.Thestringversionconsistsofacomma-separatedName,Age,ID,andSSN.Thisisshowninthefollowingcodesnippet:
//ToStringmethod
func(employeeEmployee)ToString()string{
returnfmt.Sprintf("%s:%d,%s,%d",employee.Name,employee.Age,employee.ID,employee.SSN)
}
![Page 334: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/334.jpg)
TheSortByAgetypeTheSortByAgemethodsortstheelementsconcernedbyAge.TheSortByAgeinterfaceoperatesontheEmployeearray.Thisisshowninthefollowingcodesnippet:
//SortByAgetype
typeSortByAge[]Employee
//SortByAgeinterfacemethods
func(sortIntfSortByAge)Len()int{returnlen(sortIntf)}
func(sortIntfSortByAge)Swap(iint,jint){sortIntf[i],sortIntf[j]=sortIntf[j],sortIntf[i]}
func(sortIntfSortByAge)Less(iint,jint)bool{returnsortIntf[i].Age<sortIntf[j].Age}
Themainmethodinitializestheemployeesarrayandsortsthearraybyage:
funcmain(){
varemployees=[]Employee{
{"Graham","231",235643,31},
{"John","3434",245643,42},
{"Michael","8934",32432,17},
{"Jenny","24334",32444,26},
}
![Page 335: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/335.jpg)
fmt.Println(employees)
sort.Sort(SortByAge(employees))
fmt.Println(employees)
sort.Slice(employees,func(iint,jint)bool{
returnemployees[i].Age>employees[j].Age
})
fmt.Println(employees)
}
Runthefollowingcommandtoexecutethesort_slice.gosnippet:gorunsort_slice.go
Thisistheoutput:
Anorderedlistissortedusingthesortcriteriaasfollows.Thesort_keys.gocodesnippetshowshowthingsaresortedbyvariouscriteria,suchasname,mass,anddistance.TheMassandMilesunitsaredefinedasfloat64:
///mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain
![Page 336: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/336.jpg)
//importingfmtandsortpackageimport("fmt""sort")
//MassandMilesTypestypeMassfloat64typeMilesfloat64
ThenextsectiontalksabouttheThingstructdefinition.
![Page 337: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/337.jpg)
TheThingclassAThingclassisdefinedinthefollowingcodewithname,mass,distance,meltingpoint,andfreezingpointproperties:
//ThingclasstypeThingstruct{namestringmassMassdistanceMilesmeltingpointintfreezingpointint}
ThenextsectiontalksabouttheByFactorfunctiontype.
![Page 338: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/338.jpg)
TheByFactorfunctiontypeByFactorisatypeoflessfunction.ThefollowingcodesnippetshowstheByFactortype:
//ByFactorfunctiontypetypeByFactorfunc(Thing1*Thing,Thing2*Thing)bool
![Page 339: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/339.jpg)
TheSortmethod
TheSortmethodisafunctionwiththebyFactorparameter,asshownhere://Sortmethodfunc(byFactorByFactor)Sort(Things[]Thing){varsortedThings*ThingSortersortedThings=&ThingSorter{Things:Things,byFactor:byFactor,}sort.Sort(sortedThings)}
![Page 340: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/340.jpg)
ThingsorterclassTheThingsortersortstheelementsbytheirproperties.TheThingSorterclasshasanarrayofthingsandabyFactormethod:
//ThingSorterclasstypeThingSorterstruct{Things[]ThingbyFactorfunc(Thing1*Thing,Thing2*Thing)bool}
Thenextsectiontalksabouttheimplementationofthelen,swap,andlessmethods.
![Page 341: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/341.jpg)
Thelen,swap,andlessmethodsThesort.Interfacehasthelen,swap,andlessmethods,asshowninthefollowingcode:
//Lenmethodfunc(ThingSorter*ThingSorter)Len()int{returnlen(ThingSorter.Things)}
//Swapmethodfunc(ThingSorter*ThingSorter)Swap(iint,jint){ThingSorter.Things[i],ThingSorter.Things[j]=ThingSorter.Things[j],ThingSorter.Things[i]}
//Lessmethodfunc(ThingSorter*ThingSorter)Less(iint,jint)bool{returnThingSorter.byFactor(&ThingSorter.Things[i],&ThingSorter.Things[j])}
![Page 342: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/342.jpg)
Themainmethod
Themainmethodcreatesthingsandinitializesthemwithvalues.Thismethodshowsthingsthataresortedbymass,distance,andnameindecreasingorderofdistance:
//Mainmethodfuncmain(){varThings=[]Thing{{"IronRod",0.055,0.4,3000,-180},{"SteelChair",0.815,0.7,4000,-209},{"CopperBowl",1.0,1.0,60,-30},{"BrassPot",0.107,1.5,10000,-456},}
varnamefunc(*Thing,*Thing)boolname=func(Thing1*Thing,Thing2*Thing)bool{returnThing1.name<Thing2.name}varmassfunc(*Thing,*Thing)boolmass=func(Thing1*Thing,Thing2*Thing)bool{returnThing1.mass<Thing2.mass}vardistancefunc(*Thing,*Thing)booldistance=func(Thing1*Thing,Thing2*Thing)bool{returnThing1.distance<Thing2.distance}vardecreasingDistancefunc(*Thing,*Thing)booldecreasingDistance=func(p1,p2*Thing)bool{returndistance(p2,p1)}
ByFactor(name).Sort(Things)fmt.Println("Byname:",Things)ByFactor(mass).Sort(Things)fmt.Println("Bymass:",Things)ByFactor(distance).Sort(Things)fmt.Println("Bydistance:",Things)ByFactor(decreasingDistance).Sort(Things)fmt.Println("Bydecreasingdistance:",Things)}
Runthefollowingcommandtoexecutethesort_keys.gofile:gorunsort_keys.go
Thisistheoutput:
![Page 343: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/343.jpg)
Thenextsectiontalksaboutthestructdatastructure.
![Page 344: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/344.jpg)
ThestructtypeAstructtype(class)canbesortedusingdifferentsetsofmultiplefields.Inthesort_multi_keys.gocode,weshowhowtosortstructtypes.AclasscalledCommitconsistsoftheusername,lang,andnumlinesproperties.usernameisastring,langisastring,andnumlinesisaninteger.Inthefollowingcode,theCommitclassissortedbycommitsandlines:
///mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain
//importingfmtandsortpackageimport("fmt""sort")
//ACommitisarecordofcodecheckingtypeCommitstruct{usernamestringlangstringnumlinesint}
Inthenextsection,theimplementationofthemultiSorterclassisdiscussed.
![Page 345: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/345.jpg)
ThemultiSorterclassThemultiSorterclassconsistsofthecommitsandlessFunctionarrayproperties.ThemultiSorterclassimplementstheSortinterfacetosortthecommits,asshowninthefollowingcode:
typelessFuncfunc(p1*Commit,p2*Commit)bool
//multiSorterclass
typemultiSorterstruct{
Commits[]Commit
lessFunction[]lessFunc
}
ThedifferentmethodsofthemultiSorterclassarediscussedinthefollowingsections.
![Page 346: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/346.jpg)
TheSortmethod
Inthefollowingcodesnippet,theSortmethodofmultiSortersortstheCommitsarraybyinvokingsort.SortandpassingthemultiSorterargument:
//Sortmethod
func(multiSorter*multiSorter)Sort(Commits[]Commit){
multiSorter.Commits=Commits
sort.Sort(multiSorter)
}
![Page 347: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/347.jpg)
TheOrderBymethod
TheOrderedBymethodtakesthelessfunctionandreturnsmultiSorter.Themultisorterinstanceisinitializedbythelessfunction,asshowninthefollowingcodesnippet:
//OrderedBymethod
funcOrderedBy(lessFunction...lessFunc)*multiSorter{
return&multiSorter{
lessFunction:lessFunction,
}
}
![Page 348: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/348.jpg)
Thelenmethod
ThelenmethodofthemultiSorterclassreturnsthelengthoftheCommitsarray.TheCommitsarrayisapropertyofmultiSorter:
//Lenmethodfunc(multiSorter*multiSorter)Len()int{
returnlen(multiSorter.Commits)
}
![Page 349: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/349.jpg)
TheSwapmethod
TheSwapmethodofmultiSortertakestheintegersiandjasinput.Thismethodswapsthearrayelementsatindexiandj:
//Swapmethodfunc(multiSorter*multiSorter)Swap(iint,jint){
multiSorter.Commits[i]=multiSorter.Commits[j]
multiSorter.Commits[j]=multiSorter.Commits[i]
}
![Page 350: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/350.jpg)
Thelessmethod
TheLessmethodofthemultiSorterclasstakestheintegersiandjandcomparestheelementatindexitotheelementatindexj:
func(multiSorter*multiSorter)Less(iint,jint)bool{
varp*Commitvarq*Commitp=&multiSorter.Commits[i]q=&multiSorter.Commits[j]
varkintfork=0;k<len(multiSorter.lessFunction)-1;k++{less:=multiSorter.lessFunction[k]switch{caseless(p,q):returntruecaseless(q,p):returnfalse}}returnmultiSorter.lessFunction[k](p,q)}
![Page 351: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/351.jpg)
Themainmethod
ThemainmethodcreatesaCommitarrayandinitializesthearraywithvalues.Functionsarecreatedforsortingbyuser,language,andlines.OrderedByreturnsamultiSorter,anditssortmethodiscalledbyuser,language,increasingLines,anddecreasingLines:
//mainmethodfuncmain(){varCommits=[]Commit{{"james","Javascript",110},{"ritchie","python",250},{"fletcher","Go",300},{"ray","Go",400},{"john","Go",500},{"will","Go",600},{"dan","C++",500},{"sam","Java",650},{"hayvard","Smalltalk",180},}varuserfunc(*Commit,*Commit)booluser=func(c1*Commit,c2*Commit)bool{returnc1.username<c2.username}varlanguagefunc(*Commit,*Commit)boollanguage=func(c1*Commit,c2*Commit)bool{returnc1.lang<c2.lang}varincreasingLinesfunc(*Commit,*Commit)boolincreasingLines=func(c1*Commit,c2*Commit)bool{returnc1.numlines<c2.numlines}vardecreasingLinesfunc(*Commit,*Commit)booldecreasingLines=func(c1*Commit,c2*Commit)bool{returnc1.numlines>c2.numlines//Note:>ordersdownwards.}OrderedBy(user).Sort(Commits)fmt.Println("Byusername:",Commits)OrderedBy(user,increasingLines).Sort(Commits)fmt.Println("Byusername,ascorder",Commits)OrderedBy(user,decreasingLines).Sort(Commits)fmt.Println("Byusername,descorder",Commits)OrderedBy(language,increasingLines).Sort(Commits)fmt.Println("Bylang,ascorder",Commits)OrderedBy(language,decreasingLines,user).Sort(Commits)fmt.Println("Bylang,descorder",Commits)}
Runthefollowingcommandtoexecutethesort_multi_keys.gofile:gorunsort_multi_keys.go
![Page 352: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/352.jpg)
Thisistheoutput:
ThenextsectiontalksabouttheHTMLunorderedlistdatastructure.
![Page 353: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/353.jpg)
UnorderedlistsAnunorderedlistisimplementedasalinkedlist.Inanunorderedlist,therelativepositionsofitemsincontiguousmemorydon'tneedtobemaintained.Thevalueswillbeplacedinarandomfashion.Anunorderedliststartswitha<ul>taginHTML5.0.Eachlistitemiscodedwith<li>tags.Here'sanexample:
<ul><li>Firstbook</li><li>Secondbook</li><li>Thirdbook</li></ul>
ThefollowingisanexampleofanunorderedlistinGolang.TheNodeclasshasapropertyandanextNodepointer,asshowninthefollowingcode.Thelinkedlistwillhaveasetofnodeswithapropertyattribute.Theunorderedlistispresentedinthescriptcalledunordered_list.go:
//mainpackagehasexamplesshown//inHands-OnDataStructuresandalgorithmswithGobookpackagemain
//importingfmtpackageimport("fmt")
//NodeclasstypeNodestruct{propertyintnextNode*Node}
ThenextsectiontalksabouttheUnOrderedListclassimplementation.
![Page 354: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/354.jpg)
TheUnOrderedListclassTheunorderedlistconsistsofelementsthatarenotorderedbynumbers.AnUnOrderedListclasshasaheadNodepointerastheproperty.Traversingtothenextnodefromtheheadnode,youcaniteratethroughthelinkedlist:
//UnOrderedListclass
typeUnOrderedListstruct{
headNode*Node
}
ThenextsectiondiscussestheAddtoHeadmethodandtheIterateListmethodoftheUnOrderedListstruct.
![Page 355: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/355.jpg)
TheAddtoHeadmethod
TheAddtoHeadmethodaddsthenodetotheheadoftheunorderedlist.TheAddToHeadmethodoftheUnOrderedListclasshasapropertyparameterthat'saninteger.ItwillmaketheheadNodepointtoanewnodecreatedwithproperty,andthenextNodepointstothecurrentheadNodeoftheunorderedlist:
//AddToHeadmethodofUnOrderedListclassfunc(UnOrderedList*UnOrderedList)AddToHead(propertyint){varnode=&Node{}node.property=propertynode.nextNode=nilifUnOrderedList.headNode!=nil{node.nextNode=UnOrderedList.headNode}UnOrderedList.headNode=node}
![Page 356: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/356.jpg)
TheIterateListmethod
TheIterateListmethodoftheUnOrderedListclassprintsthenodepropertyofthenodesinthelist.Thisisshowninthefollowingcode:
//IterateListmethoditeratesoverUnOrderedListfunc(UnOrderedList*UnOrderedList)IterateList(){varnode*Nodefornode=UnOrderedList.headNode;node!=nil;node=node.nextNode{fmt.Println(node.property)}}
![Page 357: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/357.jpg)
Themainmethod
Themainmethodcreatesaninstanceofalinkedlist,andintegerproperties1,3,5,and7areaddedtotheheadofthelinkedlist.Thelinkedlist'sheadNodepropertyisprintedaftertheelementsareadded:
//mainmethodfuncmain(){varunOrderedListUnOrderedListunOrderedList=UnOrderedList{}unOrderedList.AddToHead(1)unOrderedList.AddToHead(3)unOrderedList.AddToHead(5)unOrderedList.AddToHead(7)unOrderedList.IterateList()}
Runthefollowingcommandtoexecutetheunordered_list.gofilefromthecodebundle:
gorununordered_list.go
Thisistheoutput:
![Page 358: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/358.jpg)
SummaryThischaptercoveredheterogeneousdatastructuressuchasorderedlistsandunorderedlistswithcodeexamples.TheOrderedlistssectioncoveredsortingslicesbysinglekey,multiplekeys,andsort.Slice.Slicesaresortedbymakingthearrayofstructelementsimplementthesort.Sortinterface.Unorderedlistsweredescribedaslinkedlistswithvaluesthatarenotordered.Thenextchapterwillcoverdynamicdatastructuressuchasdictionaries,TreeSets,sequences,synchronizedTreeSets,andmutableTreeSets.
![Page 359: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/359.jpg)
Questions1. Whichmethodofthesort.Sortinterfacereturnsthesizeoftheelementstobesorted?
2. Whichfunctionneedstobepassedtothesort.Slicemethodtosortaslice?
3. Whatdoestheswapmethoddototheelementsattheiandjindices?4. Whatisthedefaultorderforsortingelementsusingsort.Sort?5. Howdoyouimplementascendinganddescendingsortingwith
sort.Slice?6. Howdoyousortanarrayandkeeptheoriginalorderoftheelements?7. Whichinterfaceisusedtoreversetheorderofthedata?8. Showanexampleofsortingaslice.9. Whichmethodiscalledtoaddelementstoanunorderedlist?10. Writeacodeexampleofanunorderedlistoffloats.
![Page 360: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/360.jpg)
Furtherreading
Thefollowingbooksarerecommendedifyouwanttoknowmoreaboutheterogeneousdatastructures:
DesignPatterns, byErichGamma,RichardHelm,RalphJohnson,andJohnVlissidesIntroductiontoAlgorithms –ThirdEdition,byThomasH.Cormen,CharlesE.Leiserson,RonaldL.Rivest,andCliffordSteinDatastructuresandAlgorithms:AnEasyIntroduction,by RudolphRussell
![Page 361: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/361.jpg)
DynamicDataStructuresAdynamicdatastructureisasetofelementsinmemorythathastheadaptabilitytoexpandorshrink.Thisabilityempowersasoftwareengineertocontrolpreciselyhowmuchmemoryisused.Dynamicdatastructuresareusedforhandlinggenericdatainakey-valuestore.Theycanbeusedindistributedcachingandstoragemanagement.Dynamicdatastructuresarevaluableinmanycircumstancesinwhichdynamicadditionordeletionofelementsoccur.Theyarecomparableincapacitytoasmallerrelationaldatabaseoranin-memorydatabase.Thesedatastructuresareusedinmarketingandcustomerrelationshipmanagementapplications.Dictionaries,TreeSets,andsequencesareexamplesofdynamicdatastructures.Inthischapter,wewillexplainwhatdictionaries,TreeSets,andsequencesareandshowyouhowtheyareimplementedwiththehelpofcodeexamples. Thischaptercoversthefollowing dynamicdatastructures:
DictionariesTreeSets:
SynchronizedTreeSetsMutableTreeSets
Sequences:
FareyFibonacciLook-and-sayThue–Morse
![Page 362: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/362.jpg)
TechnicalrequirementsInstallGoVersion1.10fromhttps://golang.org/doc/install foryourOS.TheGitHubURLforthecodeinthischapterisasfollows: https://github.com/PacktPublishing/Learn-Data-Structures-and-Algorithms-with-Golang/tree/master/Chapter07.
![Page 363: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/363.jpg)
DictionariesAdictionaryisacollectionofuniquekeyandvaluepairs. Adictionaryisabroadlyusefuldatastructureforstoringasetofdataitems.Ithasakey,andeachkeyhasasolitaryitemassociatedwithit.Whengivenakey,thedictionarywillrestoretheitemassociatedwiththatkey.Thesekeyscanbeofanytype:strings,integers,orobjects.Whereweneedtosortalist,anelementvaluecanberetrievedutilizingitskey. Add,remove,modify,andlookupoperationsareallowedinthiscollection.Adictionaryissimilartootherdatastructures,suchashash,map,andHashMap.Thekey/valuestoreisusedindistributedcachingandinmemorydatabases.Arraysdifferfromdictionariesinhowthedataisaccessed.Asethasuniqueitems,whereasadictionarycanhaveduplicatevalues.Dictionarydatastructuresareusedinthefollowingstreams:
PhonedirectoriesRoutertablesinnetworkingPagetablesinoperatingsystemsSymboltablesincompilersGenomemapsinbiology
Thefollowingcodeshowshowtoinitializeandmodifyadictionary. Inthissnippet,thedictionaryhasthekeyDictKeyandisastring:
//mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain
//importingfmtpackageimport("fmt""sync")
//DictKeytypetypeDictKeystring
Thefollowingsectionstalkaboutthetypeandmethodsindictionaries.
![Page 364: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/364.jpg)
DictValtypeThedictionaryhasthevalueDictValoftypestringmappedtoDictKey:
//DictValtypetypeDictValstring
![Page 365: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/365.jpg)
DictionaryclassThedictionaryinthefollowingcodeisaclasswithdictionary elements,withDictKeyas the key andDictValasthevalue.Ithasa sync.RWMutexproperty, lock:
//DictionaryclasstypeDictionarystruct{elementsmap[DictKey]DictVallocksync.RWMutex}
The Put, Remove, Contain, Find, Rest, NumberofElements,GetKeys,GetValues, andMain methodsarediscussedinthefollowingsections.
![Page 366: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/366.jpg)
Putmethod
AhasaPutmethod,asshowninthefollowingexample,thattakesthekeyandvalueparameters oftheDictKeyandDictVal typesrespectively.TheLockmethod ofthedictionary'slockinstanceisinvoked,andtheUnlockmethodisdeferred.Ifthereareemptymapelementsinthedictionary,elementsareinitializedusingmake.The map elementsaresetwithakeyandavalueiftheyarenotempty:
//Putmethodfunc(dict*Dictionary)Put(keyDictKey,valueDictVal){dict.lock.Lock()deferdict.lock.Unlock()ifdict.elements==nil{dict.elements=make(map[DictKey]DictVal)}dict.elements[key]=value}
Theexampleoutputoftheputmethodisasfollows.Theputmethodtakesthekey1andvalue1.Themapisupdatedwithkeyandvalue:
![Page 367: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/367.jpg)
Removemethod
Adictionaryhasaremovemethod,asshowninthefollowingcode,whichhasakeyparameter oftheDictKey type.ThismethodreturnsaboolvalueifthevalueassociatedwithDictkeyisremovedfromthe map:
//Removemethodfunc(dict*Dictionary)Remove(keyDictKey)bool{dict.lock.Lock()deferdict.lock.Unlock()varexistsbool_,exists=dict.elements[key]ifexists{delete(dict.elements,key)}returnexists}
![Page 368: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/368.jpg)
Containsmethod
Inthefollowingcode, the Containsmethodhasaninputparameter,key,oftheDictKey type,andreturns boolif keyexistsinthedictionary:
//Containsmethodfunc(dict*Dictionary)Contains(keyDictKey)bool{dict.lock.RLock()deferdict.lock.RUnlock()varexistsbool_,exists=dict.elements[key]returnexists}
![Page 369: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/369.jpg)
Findmethod
TheFindmethodtakesthekeyparameter oftheDictKeytype andreturnstheDictVal typeassociatedwiththekey.ThefollowingcodesnippetexplainstheFindmethod:
//Findmethodfunc(dict*Dictionary)Find(keyDictKey)DictVal{dict.lock.RLock()deferdict.lock.RUnlock()returndict.elements[key]}
![Page 370: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/370.jpg)
Resetmethod
TheResetmethodoftheDictionaryclassispresentedinthefollowingsnippet.TheLockmethod ofthedictionary'slockinstance isinvokedandUnlockisdeferred.Theelementsmapisinitializedwithamapof the DictKeykeyandthe DictValvalue:
//Resetmethodfunc(dict*Dictionary)Reset(){dict.lock.Lock()deferdict.lock.Unlock()dict.elements=make(map[DictKey]DictVal)}
![Page 371: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/371.jpg)
NumberOfElementsmethod
TheNumberOfElementsmethodoftheDictionaryclassreturnsthelengthoftheelementsmap.TheRLockmethodofthelockinstanceisinvoked.TheRUnlockmethodofthelockinstanceisdeferredbeforereturningthelength;thisisshowninthefollowingcodesnippet:
//NumberOfElementsmethodfunc(dict*Dictionary)NumberOfElements()int{dict.lock.RLock()deferdict.lock.RUnlock()returnlen(dict.elements)}
![Page 372: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/372.jpg)
GetKeysmethod
TheGetKeysmethodoftheDictionaryclassisshowninthefollowingcodesnippet.Themethodreturnsthearrayofthe DictKeyelements.TheRLockmethodofthelockinstanceisinvoked,andtheRUnlockmethodisdeferred.Thedictionarykeysarereturnedbytraversingtheelement'smap:
//GetKeysmethodfunc(dict*Dictionary)GetKeys()[]DictKey{dict.lock.RLock()deferdict.lock.RUnlock()vardictKeys[]DictKeydictKeys=[]DictKey{}varkeyDictKeyforkey=rangedict.elements{dictKeys=append(dictKeys,key)}returndictKeys}
![Page 373: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/373.jpg)
GetValuesmethod
TheGetValuesmethodoftheDictionaryclassreturnsthearrayofthe DictValelements.Inthefollowingcodesnippet,theRLockmethodofthelockinstanceisinvokedandtheRUnlockmethodisdeferred.Thearrayofdictionaryvaluesisreturnedaftertraversingtheelement'smap:
//GetValuesmethodfunc(dict*Dictionary)GetValues()[]DictVal{dict.lock.RLock()deferdict.lock.RUnlock()vardictValues[]DictValdictValues=[]DictVal{}varkeyDictKeyforkey=rangedict.elements{dictValues=append(dictValues,dict.elements[key])}returndictValues}
![Page 374: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/374.jpg)
Themainmethod
Thefollowingcodeshowsthemainmethod,wherethedictionaryisinitializedandprinted:
//mainmethodfuncmain(){vardict*Dictionary=&Dictionary{}dict.Put("1","1")dict.Put("2","2")dict.Put("3","3")dict.Put("4","4")fmt.Println(dict)}
Runthefollowingcommandstoexecutethedictionary.gofile:gorundictionary.go
Theoutputisasfollows:
Let'stakealookattheTreeSetdatastructureinthefollowingsection.
![Page 375: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/375.jpg)
TreeSetsTreeSetsareusedinmarketingandcustomerrelationshipmanagementapplications.TreeSetisasetthathasabinarytreewithuniqueelements.Theelementsaresortedinanaturalorder.Inthefollowingcodesnippet,TreeSetcreation,insertion,search,andstringifyoperationsarepresented.TreeSetallowsonlyonenullvalueifthesetisempty.Theelementsaresortedandstoredaselements.Theadd,remove,andcontainsfunctionscostlog(n)onTreeSets:
///mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain
//TreeSetclasstypeTreeSetstruct{bst*BinarySearchTree}
WewilldiscussthedifferentTreeSetmethodsinthefollowingsections.
![Page 376: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/376.jpg)
InsertTreeNodemethod
TheInsertTreeNodemethod oftheTreeSetclasstakestreeNodes variableargumentsoftheTreeNodetype.Inthefollowingcode,theelementswiththekeyandvalueareinsertedinthebinarysearchtreeof TreeSet:
//InsertTreeNodemethodfunc(treeset*TreeSet)InsertTreeNode(treeNodes...TreeNode){vartreeNodeTreeNodefor_,treeNode=rangetreeNodes{treeset.bst.InsertElement(treeNode.key,treeNode.value)}}
Theexampleoutputofthe InsertTreeNodemethodisasfollows.TheInsertTreeNodemethodtakestreeNodesastheparameter.treeNodesareinsertedwithrootNode,whichhasavalueof 8:
![Page 377: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/377.jpg)
Deletemethod
TheDeletemethodoftheTreeSetclassisshowninthefollowingcodesnippet.Inthismethod,treeNodeswiththeprovidedkeyareremoved:
//Deletemethodfunc(treeset*TreeSet)Delete(treeNodes...TreeNode){vartreeNodeTreeNodefor_,treeNode=rangetreeNodes{treeset.bst.RemoveNode(treeNode.key)}}
![Page 378: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/378.jpg)
InOrderTraverseTreemethod
TheInOrderTraverseTreemethodoftheBinarySearchTreeclasstakesfunctionasaparameter.TheRLockmethodofthelockinstanceisinvoked.The RUnlockmethodofthetree'slockinstanceisdeferred.InOrderTraverseTreeisinvokedwiththerootNodeofthetreeandfunctionasparameters:
//InOrderTraverseTreemethodfunc(tree*BinarySearchTree)InOrderTraverseTree(functionfunc(int)){tree.lock.RLock()defertree.lock.RUnlock()inOrderTraverseTree(tree.rootNode,function)}
![Page 379: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/379.jpg)
TheinOrderTraverseTreemethod
TheinOrderTraverseTreemethodtraversesfromtheleftofthetreetorootofthenodeandthentotherightofthetree.TheinOrderTraverseTreemethodtakestreeNodeandfunctionasparameters.ThemethodrecursivelycallstheinOrderTraverseTreemethodwithfunctionandthenleftNodeandrightNodeinseparatecalls.ThefunctionmethodisinvokedwiththevalueoftreeNode:
//inOrderTraverseTreemethodfuncinOrderTraverseTree(treeNode*TreeNode,functionfunc(int)){iftreeNode!=nil{inOrderTraverseTree(treeNode.leftNode,function)function(treeNode.value)inOrderTraverseTree(treeNode.rightNode,function)}}
![Page 380: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/380.jpg)
PreOrderTraverseTreemethod
ThePreOrderTraverseTreemethodoftheBinarySearchTreeclasstakesthefunctionasitsparameter.TheLockmethodonthetree'slockinstanceisinvokedfirst,andtheUnlockmethodisdeferred.ThePreOrderTraverseTreemethodiscalledwiththerootNodeofthetreeandfunctionasparameters:
//PreOrderTraversemethodfunc(tree*BinarySearchTree)PreOrderTraverseTree(functionfunc(int)){tree.lock.Lock()defertree.lock.Unlock()preOrderTraverseTree(tree.rootNode,function)}
![Page 381: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/381.jpg)
ThepreOrderTraverseTreemethod
ThepreOrderTraverseTreemethodtraversesthetreefromtheroot,totheleftandrightofthetree.ThepreOrderTraverseTreemethodtakestreeNodeandfunctionasparameters.IftreeNodeisnotnil,functionisinvokedwiththevalueoftreeNode,andthepreOrderTraverseTreemethodisinvokedwithfunction andleftNodeandrightNodeasparameters:
//preOrderTraverseTreemethodfuncpreOrderTraverseTree(treeNode*TreeNode,functionfunc(int)){iftreeNode!=nil{function(treeNode.value)preOrderTraverseTree(treeNode.leftNode,function)preOrderTraverseTree(treeNode.rightNode,function)}}
![Page 382: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/382.jpg)
Searchmethod
TheSearchmethodoftheTreeSetclasstakesa variableargumentnamedtreeNodesoftheTreeNodetype andreturnstrueifoneofthosetreeNodesexists;otherwise,itreturnsfalse.ThecodefollowingsnippetoutlinestheSearchmethod:
//Searchmethodfunc(treeset*TreeSet)Search(treeNodes...TreeNode)bool{vartreeNodeTreeNodevarexistsboolfor_,treeNode=rangetreeNodes{ifexists=treeset.bst.SearchNode(treeNode.key);!exists{returnfalse}}returntrue}
![Page 383: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/383.jpg)
TheStringmethod
Inthefollowingcodesnippet,theStringmethodoftheTreeSetclassreturnsthestringversionofbst:
//Stringmethodfunc(treeset*TreeSet)String(){treeset.bst.String()}
![Page 384: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/384.jpg)
Themainmethod
ThemainmethodintheTreeSetclasscreatesaTreeSetwithTreeNodes.ThefollowingsnippetcreatesaTreeSetandinvokestheStringmethod:
//mainmethodfuncmain(){vartreeset*TreeSet=&TreeSet{}treeset.bst=&BinarySearchTree{}varnode1TreeNode=TreeNode{8,8,nil,nil}varnode2TreeNode=TreeNode{3,3,nil,nil}varnode3TreeNode=TreeNode{10,10,nil,nil}varnode4TreeNode=TreeNode{1,1,nil,nil}varnode5TreeNode=TreeNode{6,6,nil,nil}treeset.InsertTreeNode(node1,node2,node3,node4,node5)treeset.String()}
Runthefollowingcommands toexecutethe treeset.go andbinarysearchtree.gofiles:
$gobuildtreeset.gobinarysearchtree.go
$./treeset
Theoutputisasfollows:
ThenextsectiontalksaboutthesynchronizedTreeSetdatastructure.
![Page 385: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/385.jpg)
SynchronizedTreeSetsOperationsthatareperformedonsynchronizedTreeSetsaresynchronizedacrossmultiplecallsthataccesstheelementsofTreeSets.SynchronizationinTreeSetsisachievedusingasync.RWMutexlock.Thelockmethodonthetree'slockinstanceisinvoked,andtheunlockmethodisdeferredbeforethetreenodesare inserted,deleted,orupdated:
//InsertElementmethodfunc(tree*BinarySearchTree)InsertElement(keyint,valueint){tree.lock.Lock()defertree.lock.Unlock()vartreeNode*TreeNodetreeNode=&TreeNode{key,value,nil,nil}iftree.rootNode==nil{tree.rootNode=treeNode}else{insertTreeNode(tree.rootNode,treeNode)}}
![Page 386: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/386.jpg)
Mutable TreeSetsMutableTreeSetscanuseadd,update,anddeleteoperationsonthetreeanditsnodes.insertTreeNodeupdatesthetreebytakingtherootNodeandtreeNodeparameters tobeupdated.ThefollowingcodesnippetshowshowtoinsertaTreeNodewithagivenrootNodeandTreeNode:
//insertTreeNodemethodfuncinsertTreeNode(rootNode*TreeNode,newTreeNode*TreeNode){ifnewTreeNode.key<rootNode.key{ifrootNode.leftNode==nil{rootNode.leftNode=newTreeNode}else{insertTreeNode(rootNode.leftNode,newTreeNode)}}else{ifrootNode.rightNode==nil{rootNode.rightNode=newTreeNode}else{insertTreeNode(rootNode.rightNode,newTreeNode)}}}
Let'sdiscussthedifferentmutableTreeSetsinthefollowingsections.
![Page 387: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/387.jpg)
RemoveNodemethod
TheRemoveNodemethodofaBinarySearchTreeisasfollows://RemoveNodemethodfunc(tree*BinarySearchTree)RemoveNode(keyint){tree.lock.Lock()defertree.lock.Unlock()removeNode(tree.rootNode,key)}
![Page 388: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/388.jpg)
Treeset.bstTheTreeNode'scanbeupdatedbyaccessingtreeset.bstandtraversingthebinarysearchtreefromtherootNodeandtheleftandright nodesofrootNode,asshownhere:
vartreeset*TreeSet=&TreeSet{}treeset.bst=&BinarySearchTree{}varnode1TreeNode=TreeNode{8,8,nil,nil}varnode2TreeNode=TreeNode{3,3,nil,nil}varnode3TreeNode=TreeNode{10,10,nil,nil}varnode4TreeNode=TreeNode{1,1,nil,nil}varnode5TreeNode=TreeNode{6,6,nil,nil}treeset.InsertTreeNode(node1,node2,node3,node4,node5)treeset.String()
Inthenextsection,wewilltakealookatsequences.
![Page 389: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/389.jpg)
SequencesAsequenceisasetofnumbersthataregroupedinaparticularorder.Thenumberofelementsinthestreamcanbeinfinite,andthesesequencesarecalledstreams.Asubsequenceisasequencethat'screatedfromanothersequence.Therelativepositionsoftheelementsinasubsequencewillremainthesameafterdeletingsomeoftheelementsinasequence.Inthefollowingsections,wewilltakealookatdifferentsequencessuchastheFareysequence,Fibonaccisequence,look-and-say,andThue–Morse.
![Page 390: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/390.jpg)
FareysequenceAFareysequenceconsistsofreducedfractionswithvaluesbetweenzeroandone.Thedenominatorsofthefractionsarelessthanorequaltom,andorganizedinascendingorder.ThissequenceiscalledaFareyseries.Inthefollowingcode,reducedfractionsaredisplayed:
///mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain//importingfmtpackageimport("fmt")
//fractionclasstypefractionstruct{numeratorintdenominatorint}
Let'stakealookatthedifferentmethodsinaFareysequence.
![Page 391: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/391.jpg)
Stringmethod
Thefractionclasshasthenumeratoranddenominator integerproperties.TheStringmethodofthefractionclass,asshowninthefollowingsnippet,returnsastringversionof fraction:
//stringmethodoffractionclassfunc(fracfraction)String()string{returnfmt.Sprintf("%d/%d",frac.numerator,frac.denominator)}
![Page 392: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/392.jpg)
Theg method
Thegmethodtakestwofractionsandprintstheseriesofreducedfractions.Thegfunction takesan loran rfraction,andnum intas argumentstoprintthereducedfractionasaseries.Thefollowingcodesnippetshowsthegmethod:
//gmethodfuncg(lfraction,rfraction,numint){varfracfractionfrac=fraction{l.numerator+r.numerator,l.denominator+r.denominator}iffrac.denominator<=num{g(l,frac,num)fmt.Print(frac,"")g(frac,r,num)}}
![Page 393: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/393.jpg)
Themainmethod
Thefollowingsnippetshowsthemainmethod.Inthemainmethod,reducedfractionseriesareprintedusingrecursion:
//mainmethodfuncmain(){varnumintvarlfractionvarrfractionfornum=1;num<=11;num++{l=fraction{0,1}r=fraction{1,1}fmt.Printf("F(%d):%s",num,l)g(l,r,num)fmt.Println(r)}
Runthefollowingcommandtoexecutethefarey_sequence.gofile:gorunfarey_sequence.go
Theoutputisasfollows:
![Page 394: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/394.jpg)
ThenextsectiontalksabouttheFibonaccisequencedatastructure.
![Page 395: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/395.jpg)
FibonaccisequenceTheFibonaccisequenceconsistsofalistofnumbersinwhicheverynumberisthesumofthetwoprecedingnumbers.Pingala,in200BC,wasthefirsttocomeupwithFibonaccinumbers.TheFibonaccisequenceisasfollows:
TherecurrencerelationfortheFibonaccisequenceisasfollows:
Theseedvaluesareasfollows:
AFibonacciprimeisaFibonaccinumberthatisaprimenumber.The
![Page 396: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/396.jpg)
AFibonacciprimeisaFibonaccinumberthatisaprimenumber.TheFibonacciprimeseriesisasfollows:
ComputeralgorithmssuchastheFibonaccisearchtechnique,heap,andcubesarepopularapplicationsofFibonaccinumbers.PseudorandomnumbergeneratorsuseFibonaccinumbers.Thefollowingcodesnippet showstheFibonaccisequenceandrecursiveFibonaccinumbercalculation.TheSeriesfunctionispresentedaswell.TheSeriesfunctioncalculatestheFibonaccinumbersinthesequence:
///mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain
//importingfmtandstrconvpackageimport("fmt""strconv")
//SeriesmethodfuncSeries(nint)int{varf[]intf=make([]int,n+1,n+2)ifn<2{f=f[0:2]}f[0]=0f[1]=1variintfori=2;i<=n;i++{f[i]=f[i-1]+f[i-2]}returnf[n]}
ThedifferentmethodsoftheFibonaccisequencearediscussedinthefollowingsections.
![Page 397: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/397.jpg)
FibonacciNumbermethod
TheFibonacciNumbermethodtakestheintegernand,byrecursion,calculatestheFibonaccinumbers.Thefollowingcodesnippetshowsthisrecursion:
//FibonacciNumbermethodfuncFibonacciNumber(nint)int{ifn<=1{returnn}returnFibonacciNumber(n-1)+FibonacciNumber(n-2)}
![Page 398: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/398.jpg)
Mainmethod
ThemainmethodinthefollowingcodesnippetshowshowtheFibonaccisequenceiscalculated:
//mainmethodfuncmain(){variintfori=0;i<=9;i++{fmt.Print(strconv.Itoa(Series(i))+"")}fmt.Println("")fori=0;i<=9;i++{fmt.Print(strconv.Itoa(FibonacciNumber(i))+"")}fmt.Println("")}
Runthefollowingcommandtoexecutethefibonacci_sequence.gofile:gorunfibonacci_sequence.go
Theoutputisasfollows:
Thenextsectiontalksaboutthelook-and-saydatastructure.
![Page 399: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/399.jpg)
Look-and-sayThelook-and-saysequenceisasequenceofintegers:
Thesequenceisgeneratedbycountingthedigitsofthepreviousnumberinthegroup.JohnConwayinitiallycoinedthetermlook-and-saysequence.Thelook-and-saysequenceisshowninthefollowingcode.Thelook_saymethodtakesastringasaparameterandreturnsalook-and-saysequenceofintegers:
//mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain
//importingfmtandstrconvpackageimport("fmt""strconv")
//look_saymethodfunclook_say(strstring)(rstrstring){varcbytebytecbyte=str[0]varincintinc=1variintfori=1;i<len(str);i++{vardbytebytedbyte=str[i]ifdbyte==cbyte{inc++continue}rstr=rstr+strconv.Itoa(inc)+string(cbyte)cbyte=dbyte
![Page 400: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/400.jpg)
cbyte=dbyte
inc=1}returnrstr+strconv.Itoa(inc)+string(cbyte)}
Themainmethodinitializesthe stringandinvokesthelook_saymethod.Thelook-and-saysequencethatisreturnedfromthemethodisprinted:
//mainmethodfuncmain(){varstrstringstr="1"fmt.Println(str)variintfori=0;i<8;i++{str=look_say(str)fmt.Println(str)}}
Runthefollowingcommandtoexecutethelook_say.gofile:gorunlook_say.go
Theoutputisasfollows:
ThenextsectiontalksabouttheThue–Morsedatastructure.
![Page 401: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/401.jpg)
Thue–MorseThe Thue–MorsesequenceisabinarysequencestartingatzerothatappendstheBooleancomplementofthecurrentsequence.TheThue–Morsesequence isasfollows:
TheThue–MorsesequencewasappliedbyEugeneProphetandusedbyAxelThueinthestudyofcombinatoricsonwords.TheThue–Morsesequenceisusedintheareaoffractalcurves,suchasKochsnowflakes.ThefollowingcodesnippetcreatestheThue–Morsesequence.TheThueMorseSequencefunction takesabytes.BufferinstancebufferandmodifiesthebuffertotheThue–Morsesequencebyapplyingthecomplementoperationonthebytes:
//mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain
//importingfmtandbytespackageimport("bytes""fmt")
//ThueMorseSequencemethodfuncThueMorseSequence(buffer*bytes.Buffer){
varbintvarcurrLengthintvarcurrBytes[]byteforb,currLength,currBytes=0,buffer.Len(),buffer.Bytes();b<currLength;b++{ifcurrBytes[b]=='1'{buffer.WriteByte('0')
![Page 402: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/402.jpg)
buffer.WriteByte('0')
}else{buffer.WriteByte('1')}}}
Themainmethodinitializesthesequencenumberas0.TheThueMorseSequencemethodtakesthepointertothebytes.BufferandmodifiesitbyinvokingtheThueMorseSequencemethod.TheresultingsequenceisprintedontheTerminal:
//mainmethodfuncmain(){varbufferbytes.Buffer//initialsequencememberis"0"buffer.WriteByte('0')fmt.Println(buffer.String())variintfori=2;i<=7;i++{ThueMorseSequence(&buffer)fmt.Println(buffer.String())}}
Runthefollowingcommandtoexecutethethue_morse.gofile:gorunthue_morse.go
Theoutputisasfollows:
![Page 403: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/403.jpg)
SummaryThischaptercoveredthecontains,put,remove,find,reset,NumberOfElements,getKeys,andgetValuesmethodsofthedictionarydatastructure.TheInsertTreeNode,Delete,Search,andstringifyTreeSetoperations havebeen explainedindetail,andcodeexampleswereprovided.TheBinarySearchTreestructurehasbeenpresentedincode,alongwiththeInsertElement,InOrderTraversal,PreOrderTraverseTree,SearchNode,andRemoveNodefunctions.Thenextchaptercoversalgorithmssuchassorting,searching,recursion,andhashing.
![Page 404: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/404.jpg)
Questions1. HowdoyouensureaBinarySearchTreeissynchronized?2. Whichmethodiscalledtopostponetheinvocationofafunction?3. Howdoyoudefinedictionarykeysandvalueswithcustomtypes?4. Howdoyoufindthelengthofamap?5. WhatkeywordisusedtotraversealistoftreeNodesinatree?6. InaFareysequence,whataretherealnumbersintheseriescalled?7. WhatisaFibonaccinumber?8. Howdoyouconvertanintegerintoastring?9. Whatmethodisusedtoconvertabyteintoastring?10. Whatmethodiscalledtoaddelementstoadictionary?
![Page 405: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/405.jpg)
Furtherreading
Thefollowingbooksarerecommendedifyouwanttolearnmoreaboutdynamicdatastructures:
DesignPatterns, byErichGamma,RichardHelm,RalphJohnson,andJohnVlissidesIntroductiontoAlgorithms –ThirdEdition,byThomasH.Cormen,CharlesE.Leiserson,RonaldL.Rivest,andCliffordSteinDatastructuresandAlgorithms:AnEasyIntroduction,by RudolphRussell
![Page 406: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/406.jpg)
ClassicAlgorithmsClassicalgorithmsareusedintheareasofdatasearchandcryptography.Sorting,searching,recursing,andhashingalgorithmsaregoodexamplesofclassicalgorithms. Sortingalgorithmsareusedtoorderelementsintoeitheranascendingordescending keyarrangement.Thesealgorithmsarefrequentlyusedtocanonicalizedataandtocreatereadablecontent.Searchalgorithmsareusedtofindanelementinaset.Arecursivealgorithmisonethatcallsitselfwithinputitems. Ahashingalgorithmisacryptographichashtechnique.Itisascientificcalculationthatmapsdatawithasubjectivesizetoahashwithasettledsize.It'sintendedtobeasingledirectionfunction,thatyoucannotalter.Inthischapter,wewillcoverthedifferentclassicalgorithmsandexplainthemwithsuitableexamples.Thischaptercoversthefollowingalgorithms:
Sorting:BubbleSelectionInsertionShellMergeQuick
Searching:LinearSequentialBinaryInterpolation
RecursionHashing
![Page 407: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/407.jpg)
TechnicalrequirementsInstallGoversion1.10fromhttps://golang.org/doc/installforyourOS.TheGitHubURLforthecodeinthischapterisasfollows: https://github.com/PacktPublishing/Learn-Data-Structures-and-Algorithms-with-Golang/tree/master/Chapter08.
![Page 408: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/408.jpg)
Sorting
Sortingalgorithmsarrangetheelementsinacollectioninascendingordescendingorder.Lexicographicalordercanbeappliedtoacollectionofcharactersandstrings.Theefficiencyofthesealgorithmsisintheperformanceofsortingtheinputdataintoasortedcollection.Thebestsortingalgorithm timecomplexityisO(nlogn).Sorting algorithmsareclassifiedbythefollowingcriteria:
ComputationalcomplexityMemoryusageStabilityTypeofsorting:serial/parallelAdaptabilityMethodofsorting
Inthefollowingsections,we'lllookatthedifferentsortingalgorithms,thatis,bubble,selection,insertion,shell,merge,andquick.
![Page 409: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/409.jpg)
BubbleThebubblesortalgorithmisasortingalgorithmthatcomparesapairofneighboringelementsandswapsthemiftheyareinthewrongorder.ThealgorithmhasacomplexityofO(n2),wherenisthenumberofelementstobesorted.Thesmallestorgreatestvaluebubblesuptothetopofthecollection,orthesmallestorgreatestsinkstothebottom(dependingonwhetheryou'resortingintoascendingordescendingorder).Thefollowingcodesnippetshowstheimplementationofthebubblesortalgorithm.ThebubbleSorterfunctiontakesanintegerarrayandsortsthearray'selementsinascendingorder. Themainmethodinitializesthearray'sintegersandinvokesthebubbleSorter function,asfollows:
//mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain
//importingfmtandbytespackageimport("fmt")
//bubbleSortermethodfuncbubbleSorter(integers[11]int){
varnumintnum=11varisSwappedboolisSwapped=trueforisSwapped{isSwapped=falsevariintfori=1;i<num;i++{ifintegers[i-1]>integers[i]{
vartemp=integers[i]integers[i]=integers[i-1]integers[i-1]=tempisSwapped=true}}}fmt.Println(integers)}
![Page 410: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/410.jpg)
//mainmethodfuncmain(){varintegers[11]int=[11]int{31,13,12,4,18,16,7,2,3,0,10}fmt.Println("BubbleSorter")bubbleSorter(integers)
}
Runthefollowingcommandtoexecutethebubble_sort.gofile:gorunbubble_sort.go
Theoutputisasfollows:
Let'stakealookattheselectionsortalgorithminthefollowingsection.
![Page 411: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/411.jpg)
Selection
Selectionsortisanalgorithmthatdividestheinputcollectionintotwofragments.Thissublistofelementsissortedbyswappingthesmallestorlargestelementfromtheleftofthelisttotheright.ThealgorithmisoftheorderO(n2).Thisalgorithmisinefficientforlargecollections,anditperformsworsethantheinsertionsortalgorithm.Thefollowingcodeshowstheimplementationofthe SelectionSorterfunction,whichtakesthecollectiontobesorted:
//mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain
//importingfmtpackageimport("fmt")
//SelectionSortermethodfuncSelectionSorter(elements[]int){
variintfori=0;i<len(elements)-1;i++{varminintmin=ivarjintforj=i+1;j<=len(elements)-1;j++{ifelements[j]<elements[min]{min=j}}swap(elements,i,min)}}
Let'stakealookatthedifferentselectionmethodsinthenextsections.
![Page 412: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/412.jpg)
Theswapmethod
Theswapmethodtakestheelementsarrayandthe iandjindicesasparameters.Themethodswapstheelementatpositioniwiththeelementatposition j,asshownhere:
//swapmethodfuncswap(elements[]int,iint,jint){vartempinttemp=elements[j]elements[j]=elements[i]elements[i]=temp}
![Page 413: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/413.jpg)
Themainmethod
Themainmethodinitializestheelementsarray.The elementsareprintedbeforeandaftersortinginthefollowingcodesnippet:
//mainmethodfuncmain(){varelements[]intelements=[]int{11,4,18,6,19,21,71,13,15,2}fmt.Println("BeforeSorting",elements)SelectionSorter(elements)fmt.Println("AfterSorting",elements)}
Runthefollowingcommand toexecutetheselection_sort.gofile:gorunselection_sort.go
Theoutputisasfollows:
Let'stakealookattheinsertionsortalgorithminthefollowingsection.
![Page 414: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/414.jpg)
Insertion
Insertionsortisanalgorithmthatcreatesafinalsortedarrayoneelementatatime.Thealgorithm'sperformanceisoftheorderO(n2).Thisalgorithmislessefficientonlargecollectionsthanotheralgorithms,suchasquick,heap,andmergesort.Inreallife,agoodexampleofinsertionsortisthewaycardsaremanuallysortedbytheplayers inagameofbridge.Theimplementationoftheinsertionsortalgorithmisshowninthefollowingcodesnippet.TheRandomSequencefunctiontakesthenumberofelementsasaparameterandreturnsanarrayofrandomintegers:
//mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain
//importingfmtandbytespackageimport("fmt""math/rand""time")
//randomSequencemethodfuncrandomSequence(numint)[]int{
varsequence[]intsequence=make([]int,num,num)rand.Seed(time.Now().UnixNano())variintfori=0;i<num;i++{sequence[i]=rand.Intn(999)-rand.Intn(999)}returnsequence}
Let'stakealookatthedifferentinsertionmethodsinthenextsections.
![Page 415: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/415.jpg)
InsertionSortermethod
TheimplementationoftheInsertionSortermethodisshowninthefollowingsnippet.Thismethodtakesthearray of integersasaparameterandsortsthem:
//InsertionSortermethodfuncInsertionSorter(elements[]int){varn=len(elements)variint
fori=1;i<n;i++{varjintj=iforj>0{ifelements[j-1]>elements[j]{elements[j-1],elements[j]=elements[j],elements[j-1]}j=j-1}}}
![Page 416: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/416.jpg)
Themainmethod
ThemainmethodinitializesthesequencebyinvokingtherandomSequencefunction,asshowninthefollowingcode.TheInsertionSorterfunctiontakesthesequenceandsortsitinascendingorder:
//mainmethodfuncmain(){
varsequence[]intsequence=randomSequence(24)fmt.Println("\n^^^^^^BeforeSorting^^^\n\n",sequence)InsertionSorter(sequence)fmt.Println("\n---AfterSorting---\n\n",sequence,"\n")}
Runthefollowingcommand toexecutetheinsertion_sort.gofile:goruninsertion_sort.go
Theoutputisasfollows:
Let'stakealookattheshellsort algorithminthenextsection.
![Page 417: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/417.jpg)
ShellTheshellsortalgorithmsortsapairofelementsthatare notinsequence inacollection.Thedistancebetweentheelementstobecomparedisdecreasedsequentially.Thisalgorithmperformsmoreoperationsandhasagreater cachemissratiothanthequicksortalgorithm.Inthefollowingcode, wecanseetheimplementationofthe shellsort algorithm.TheShellSorterfunctiontakesanintegerarrayasaparameterandsortsit:
//mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain
//importingfmtandbytespackageimport("fmt")
//shellsortermethodfuncShellSorter(elements[]int){var(n=len(elements)intervals=[]int{1}k=1
)
for{varintervalintinterval=power(2,k)+1ifinterval>n-1{break}intervals=append([]int{interval},intervals...)k++}varintervalintfor_,interval=rangeintervals{variintfori=interval;i<n;i+=interval{varjintj=iforj>0{ifelements[j-interval]>elements[j]{elements[j-interval],elements[j]=elements[j],elements[j-interval]
![Page 418: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/418.jpg)
interval]
}j=j-interval}}}}
Let'stakealookatthedifferentshellmethodsinthefollowingsections.
![Page 419: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/419.jpg)
Thepowermethod
Thepowermethodtakesexponentandindexasparametersandreturnsthepoweroftheexponenttotheindex,asfollows:
//powerfunctionfuncpower(exponentint,indexint)int{varpowerintpower=1forindex>0{ifindex&1!=0{power*=exponent}index>>=1exponent*=exponent}returnpower}
![Page 420: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/420.jpg)
Themainmethod
ThemainmethodinitializestheelementsintegerarrayandinvokestheShellSortermethod,asfollows:
//mainmethodfuncmain(){varelements[]intelements=[]int{34,202,13,19,6,5,1,43,506,12,20,28,17,100,25,4,5,97,1000,27}ShellSorter(elements)fmt.Println(elements)}
Runthefollowingcommand toexecutetheshell_sort.gofile:gorunshell_sort.go
Theoutputisasfollows:
Let'stakealookatthemergesort algorithminthenextsection.
![Page 421: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/421.jpg)
MergeThemergesortalgorithmisacomparison-basedmethodthatwasinventedbyJohnVonNeumann.Eachelementintheadjacentlistiscomparedforsorting. TheperformanceofthealgorithmisintheorderofO(nlogn).Thisalgorithmisthebestalgorithmforsortingalinkedlist.Thefollowingcodesnippetdemonstratesthemergesortalgorithm. ThecreateArrayfunctiontakesnumintasaparameterandreturnsaninteger, array,thatconsistsofrandomizedelements:
//mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain
//importingfmtandbytespackageimport("fmt""math/rand""time")
//createarrayfunccreateArray(numint)[]int{vararray[]intarray=make([]int,num,num)rand.Seed(time.Now().UnixNano())variintfori=0;i<num;i++{array[i]=rand.Intn(99999)-rand.Intn(99999)}returnarray}
Let'stakealookatthedifferentmergemethodsinthefollowingsections.
![Page 422: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/422.jpg)
MergeSortermethod
TheMergeSortermethodtakesanarrayofintegerelements asaparameter, andtwosub-arraysofelementsarerecursivelypassedtotheMergeSortermethod.Theresultantarraysarejoinedandreturnedasthecollection,asfollows:
//MergeSorteralgorithmfuncMergeSorter(array[]int)[]int{
iflen(array)<2{returnarray}varmiddleintmiddle=(len(array))/2returnJoinArrays(MergeSorter(array[:middle]),MergeSorter(array[middle:]))}
![Page 423: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/423.jpg)
JoinArraysmethod
TheJoinArraysfunctiontakesthe leftArrandrightArrintegerarraysasparameters.Thecombinedarrayisreturnedinthefollowingcode:
//JoinArraysmethodfuncJoinArrays(leftArr[]int,rightArr[]int)[]int{
varnumintvariintvarjintnum,i,j=len(leftArr)+len(rightArr),0,0vararray[]intarray=make([]int,num,num)
varkintfork=0;k<num;k++{ifi>len(leftArr)-1&&j<=len(rightArr)-1{array[k]=rightArr[j]j++}elseifj>len(rightArr)-1&&i<=len(leftArr)-1{array[k]=leftArr[i]i++}elseifleftArr[i]<rightArr[j]{array[k]=leftArr[i]i++}else{array[k]=rightArr[j]j++}}returnarray}
![Page 424: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/424.jpg)
Themainmethod
Themainmethodinitializestheintegerarrayof40elements,andtheelementsareprintedbeforeandaftersorting,asfollows:
//mainmethodfuncmain(){
varelements[]intelements=createArray(40)fmt.Println("\nBeforeSorting\n\n",elements)fmt.Println("\n-AfterSorting\n\n",MergeSorter(elements),"\n")}
Runthefollowingcommand toexecutethemerge_sort.gofile:gorunmerge_sort.go
Theoutputisasfollows:
Let'stakealookatthequicksort algorithminthefollowingsection.
![Page 425: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/425.jpg)
QuickQuicksortisanalgorithmforsortingtheelementsofacollectioninanorganizedway. Parallelized quicksortistwotothreetimesfasterthanmergesortandheapsort.Thealgorithm'sperformanceisoftheorderO(nlogn). Thisalgorithmisaspace-optimizedversionofthebinarytreesortalgorithm.Inthefollowingcodesnippet,thequicksortalgorithmisimplemented.TheQuickSorterfunctiontakesanarrayofintegerelements,upperint,andbelowint asparameters.Thefunctiondividesthearrayintoparts,whicharerecursivelydividedandsorted:
//mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain
//importingfmtpackageimport("fmt")
//QuickSortermethodfuncQuickSorter(elements[]int,belowint,upperint){ifbelow<upper{varpartintpart=divideParts(elements,below,upper)QuickSorter(elements,below,part-1)QuickSorter(elements,part+1,upper)}}
Let'stakealookatthedifferentquickmethodsinthefollowingsections.
![Page 426: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/426.jpg)
ThedividePartsmethod
ThedividePartsmethodtakesanarrayofintegerelements,upperint,andbelowint asparameters.Themethodsortstheelementsinascendingorder,asshowninthefollowingcode:
//dividePartsmethodfuncdivideParts(elements[]int,belowint,upperint)int{varcenterintcenter=elements[upper]variinti=belowvarjintforj=below;j<upper;j++{ifelements[j]<=center{swap(&elements[i],&elements[j])i+=1}}swap(&elements[i],&elements[upper])returni}
![Page 427: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/427.jpg)
Theswapmethod
Inthefollowingcodesnippet,theswapmethodexchangeselementsbyinterchangingthevalues:
//swapmethodfuncswap(element1*int,element2*int){varvalintval=*element1*element1=*element2*element2=val}
![Page 428: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/428.jpg)
Themainmethod
Themainmethodaskstheusertoinputthenumberofelementsandtheelementstoberead.Thearrayisinitializedandprintedbeforeandaftersorting,asfollows:
//mainmethodfuncmain(){varnumint
fmt.Print("EnterNumberofElements:")fmt.Scan(&num)
vararray=make([]int,num)
variintfori=0;i<num;i++{fmt.Print("array[",i,"]:")fmt.Scan(&array[i])}
fmt.Print("Elements:",array,"\n")QuickSorter(array,0,num-1)fmt.Print("SortedElements:",array,"\n")}
Runthefollowingcommandtoexecutethequick_sort.gofile:gorunquick_sort.go
Theoutputisasfollows:
![Page 429: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/429.jpg)
Nowthatwearedonewithsortalgorithms,let'stakealookatthesearchalgorithmsinthenextsection.
![Page 430: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/430.jpg)
Searching
Searchalgorithmsareusedtoretrieveinformationthat'sstoredinadatasourceoracollection.Thealgorithmisgiventhekeyoftheelementinquestion,and theassociatedvalue willbefound. SearchalgorithmsreturnatrueorafalseBooleanvaluebasedontheavailabilityoftheinformation.Theycanbeenhancedtodisplaymultiplevaluesrelatedtothesearchcriteria.Differenttypesofsearchalgorithmsincludelinear,binary,andinterpolation.Thesealgorithmsarecategorizedbythetypeofsearch.Searchalgorithmsincludebruteforceandheuristicmethods.Thealgorithmsarechosenfortheirefficiency.Differentfactorsforchoosingthesealgorithmsareasfollows:
InputtypeOutputtypeDefinitenessCorrectnessFinitenessEffectivenessGenerality
Inthissection,wewilldiscussthedifferenttypesofsearchalgorithms.
![Page 431: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/431.jpg)
LinearThelinearsearchmethodfindsagivenvaluewithinacollectionbysequentially checkingeveryelementinthecollection.ThetimecomplexityofthelinearsearchalgorithmisO(n).Thebinarysearchalgorithmandhashtablesperformbetterthanthissearchalgorithm.Theimplementationofthelinearsearchmethodisshowninthefollowingcodesnippet.The LinearSearchfunctiontakesanarray of integerelementsandfindElementintasparameters.ThefunctionreturnsaBooleantrueifthefindElementisfound;otherwise,itreturnsfalse:
//mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain
//importingfmtpackageimport("fmt")
//LinearSearchmethodfuncLinearSearch(elements[]int,findElementint)bool{varelementintfor_,element=rangeelements{ifelement==findElement{returntrue}}returnfalse}
Themainmethodinitializesthearray of integerelementsandinvokestheLinearSearchmethodbypassinganintegerthatneedstobefound,asfollows:
//mainmethodfuncmain(){varelements[]intelements=[]int{15,48,26,18,41,86,29,51,20}fmt.Println(LinearSearch(elements,48))}
Runthefollowingcommandtoexecutethelinear_search.gofile:gorunlinear_search.go
![Page 432: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/432.jpg)
Theoutputisasfollows:
Let'stakealookatthebinarysearch algorithminthefollowingsection.
![Page 433: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/433.jpg)
BinaryThebinarysearchalgorithmcomparestheinputvaluetothemiddleelementofthesortedcollection.Ifthevaluesarenotequal,thehalfinwhichtheelementisnotfoundiseliminated.Thesearchcontinuesontheremaininghalfofthecollection.Thetimecomplexityofthisalgorithmisintheorderof O(logn).Thefollowingcodesnippetshowsanimplementationofthebinarysearchalgorithmusingthesort.Searchfunctionfromthesortpackage.Themainmethodinitializestheelementsarrayandinvokesthesort.Searchfunctiontofindanintegerelement:
//mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain
//importingfmtpackageimport("fmt""sort")
//mainmethodfuncmain(){varelements[]intelements=[]int{1,3,16,10,45,31,28,36,45,75}varelementintelement=36
variint
i=sort.Search(len(elements),func(iint)bool{returnelements[i]>=element})ifi<len(elements)&&elements[i]==element{fmt.Printf("foundelement%datindex%din%v\n",element,i,elements)}else{fmt.Printf("element%dnotfoundin%v\n",element,elements)}}
Runthefollowingcommandtoexecutethebinary_search.gofile:gorunbinary_search.go
![Page 434: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/434.jpg)
Theoutputisasfollows:
Let'stakealookattheinterpolationsearch algorithminthefollowingsection.
![Page 435: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/435.jpg)
Interpolation
Theinterpolationsearchalgorithmsearchesfortheelementinasortedcollection.Thealgorithmfindstheinputelementatanestimatedpositionbydiminishingthesearchspacebeforeoraftertheestimatedposition.ThetimecomplexityofthesearchalgorithmisoftheorderO(loglogn).Thefollowingcodesnippetimplementstheinterpolationsearchalgorithm.TheInterpolationSearchfunctiontakesthearrayofintegerelementsandtheintegerelementtobefoundasparameters.ThefunctionfindstheelementinthecollectionandreturnstheBooleanandtheindexforthefoundelement:
//mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain
//importingfmtpackageimport("fmt")
//interpolationsearchmethodfuncInterpolationSearch(elements[]int,elementint)(bool,int){varmidintvarlowintlow=0varhighinthigh=len(elements)-1
forelements[low]<element&&elements[high]>element{mid=low+((element-elements[low])*(high-low))/(elements[high]-elements[low])
ifelements[mid]<element{low=mid+1}elseifelements[mid]>element{high=mid-1}else{returntrue,mid}}
ifelements[low]==element{returntrue,low}elseifelements[high]==element{returntrue,high}else{
![Page 436: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/436.jpg)
}else{
returnfalse,-1}
returnfalse,-1}
ThemainmethodinitializesthearrayofintegerelementsandinvokestheInterpolationSearchmethod withtheelementsarrayandtheelementparameters,asfollows:
//mainmethodfuncmain(){varelements[]intelements=[]int{2,3,5,7,9}varelementintelement=7varfoundboolvarindexintfound,index=InterpolationSearch(elements,element)fmt.Println(found,"foundat",index)}
Runthefollowingcommandtoexecutetheinterpolation_search.gofile:goruninterpolation_search.go
Theoutputisasfollows:
Nowthatwearedonewithsearchalgorithms,let'stakealookattherecursionalgorithmsinthenextsection.
![Page 437: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/437.jpg)
Recursion
Recursionisanalgorithminwhichoneofthestepsinvokesthecurrentlyrunningmethodorfunction. Thisalgorithmacquirestheoutcomefortheinputbyapplyingbasictasksandthenreturnsthevalue.ThismethodwasbrieflydiscussedintheDivideandconqueralgorithmssectionofChapter1,DataStructuresandAlgorithms.Duringrecursion,ifthebaseconditionisnotreached,thenastackoverflowconditionmayarise.Arecursionalgorithmisimplementedinthefollowingcodesnippet.TheFactormethodtakesthenumasaparameterandreturnsthefactorialofnum.Themethodusesrecursiontocalculatethefactorialofthenumber:
//mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain
//importingfmtandbytespackageimport("fmt")
//factorialmethodfuncFactor(numint)int{ifnum<=1{return1}returnnum*Factor(num-1)}
Themainmethoddefinestheintegerwithavalueof 12 andinvokestheFactormethod.Thefactorialofthenumber12isprinted,asshowninthefollowingcode:
//mainmethodfuncmain(){varnumint=12fmt.Println("Factorial:%dis%d",num,Factor(num))}
Runthefollowingcommandtoexecutetherecurse_factorial.gofile:gorunrecurse_factorial.go
Theoutputisasfollows:
![Page 438: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/438.jpg)
Nowthatwearedonewithrecursivealgorithms,let'stakealookatthehashalgorithmsinthenextsection.
![Page 439: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/439.jpg)
Hashing
HashfunctionswereintroducedinChapter4,Non-LinearDataStructures. HashimplementationinGohascrc32andsha256implementations.AnimplementationofahashingalgorithmwithmultiplevaluesusinganXORtransformationisshowninthefollowingcodesnippet. TheCreateHashfunctiontakesabytearray, byteStr,asaparameterandreturnsthe sha256checksumofthebytearray:
//mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain
//importingfmtpackageimport("fmt""crypto/sha1""hash")
//CreateHashmethodfuncCreateHash(byteStr[]byte)[]byte{varhashValhash.HashhashVal=sha1.New()hashVal.Write(byteStr)
varbytes[]byte
bytes=hashVal.Sum(nil)returnbytes}
Inthefollowingsections,wewilldiscussthedifferentmethodsofhashalgorithms.
![Page 440: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/440.jpg)
TheCreateHashMutliplemethod
TheCreateHashMutliplemethodtakesthebyteStr1andbyteStr2bytearraysasparametersandreturnstheXOR-transformedbytesvalue,asfollows:
//CreatehashforMultipleValuesmethodfuncCreateHashMultiple(byteStr1[]byte,byteStr2[]byte)[]byte{returnxor(CreateHash(byteStr1),CreateHash(byteStr2))}
![Page 441: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/441.jpg)
The XORmethod
ThexormethodtakesthebyteStr1andbyteStr2bytearraysasparametersandreturnstheXOR-transformationresult,asfollows:
//XORmethodfuncxor(byteStr1[]byte,byteStr2[]byte)[]byte{varxorbytes[]bytexorbytes=make([]byte,len(byteStr1))variintfori=0;i<len(byteStr1);i++{xorbytes[i]=byteStr1[i]^byteStr2[i]}returnxorbytes}
![Page 442: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/442.jpg)
Themainmethod
ThemainmethodinvokesthecreateHashMutliplemethod,passingCheck andHash as stringparameters,andprintsthehashvalueofthestrings,asfollows:
//mainmethodfuncmain(){
varbytes[]bytebytes=CreateHashMultiple([]byte("Check"),[]byte("Hash"))
fmt.Printf("%x\n",bytes)}
Runthefollowingcommandtoexecutethehash.gofile:gorunhash.go
Theoutputisasfollows:
![Page 443: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/443.jpg)
SummaryThischaptercoveredsortingalgorithmssuchasbubble,selection,insertion,shell,merge,andquicksort.Searchalgorithmssuchaslinear,binary,andinterpolationwerethediscussed.Finally,therecursionandhashingalgorithmswereexplainedwithcodesnippets.Allofthealgorithmswerediscussedalongside codeexamplesandperformanceanalysis.Inthenextchapter,networkrepresentationusinggraphsandsparsematrixrepresentationusinglistoflistswillbe covered,alongwithappropriateexamples.
![Page 444: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/444.jpg)
Questions1. Whatistheorderofcomplexityofbubblesort?2. Whichsortingalgorithmtakesoneelementatatimetocreateafinalsortedcollection?
3. Whatsortingmethodsortspairsofelementsthatarefarapartfromeachother?
4. Whatisthecomplexityofusingthemergesortalgorithm?5. Whichisbetter:thequick,merge,orheapsortalgorithm?6. Whatarethedifferenttypesofsearchalgorithms?7. Provideacodeexampleoftherecursionalgorithm.8. Whowasthefirstpersontodescribetheinterpolationsearch?9. Whichsortingalgorithmisbasedonacomparison-basedmethodofanadjacentlistofelements?
10. Whowasthepersontopublishtheshellsortalgorithm?
![Page 445: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/445.jpg)
Furtherreading
Thefollowingbooksarerecommendedifyouwanttoknowmoreaboutalgorithmssuchassorting,selecting,searching,andhashing:
DesignPatterns, byErichGamma,RichardHelm,RalphJohnson,andJohnVlissidesIntroductiontoAlgorithms –ThirdEdition,byThomasH.Cormen,CharlesE.Leiserson,RonaldL.Rivest,andCliffordSteinDatastructuresandAlgorithms:AnEasyIntroduction,by RudolphRussell
![Page 446: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/446.jpg)
Section3:AdvancedDataStructuresandAlgorithmsusingGo
Networkrepresentation,sparsematrixrepresentation,memorymanagement,instancebasedlearning,compilertranslation,andprocessscheduling-relateddatastructuresandalgorithmsarepresentedinthissection.Thedatastructuresshowninthealgorithmsaregraphs,listoflists,AVLtrees,K-Dtrees,balltrees,VanEmdeBoastrees,buffertrees,andred-blacktrees.Cache-obliviousdatastructuresanddataflowanalysisarecoveredwithcodeexamplesandefficiencyanalysis.Thissectioncontainsthefollowingchapters:
Chapter9, NetworkandSparseMatrixRepresentationChapter10, MemoryManagement
![Page 447: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/447.jpg)
NetworkandSparseMatrixRepresentation
Asparsematrixisamatrixinwhichmostofthevaluesarezero.Theratioofzerovaluestonon-zerovaluesisknownasthesparsity.Anestimationofamatrix'ssparsitycanbehelpfulwhencreatinghypothesesabouttheavailabilityofnetworks.Extensivebigsparsematricesarecommonlyusedinmachinelearningandnaturallanguageparsing.Itiscomputationallycostlytoworkwiththem.Recommendationenginesusethemforrepresenting productsinsideacatalog.Computervisionuses sparsematricesandnetworkdatastructures whenworkingwithpicturesthatcontainsectionswithdarkpixels.Networkandsparsematrixdatastructuresarealsousedinsocialgraphsandmaplayouts.Inthischapter,wewillcoverthefollowingtopics:
Networkrepresentationsusinggraphs:SocialnetworkrepresentationMaplayoutsKnowledgegraphs
Sparsematrixrepresentationusingalistoflists
Asocialgraphthatconnectspeopleisimplemented inthischapter, andacodeexampleshowshowthegraphcanbetraversed.Maplayoutsareexplainedwithgeographiclocationswithlatitudeandlongitude.Knowledgegraphsareexplainedviatheuseofacaranditsparts.
![Page 448: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/448.jpg)
TechnicalrequirementsInstallGoversion1.10fromhttps://golang.org/doc/installforyourOS.TheGitHubURLforthecodeinthischapterisasfollows: https://github.com/PacktPublishing/Learn-Data-Structures-and-Algorithms-with-Golang/tree/master/Chapter09.
![Page 449: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/449.jpg)
NetworkrepresentationusinggraphsAgraphisarepresentationofasetofobjectsthat'sconnectedbylinks.Thelinksconnectvertices,whicharepoints.Thebasicoperationsonagrapharetheadditionandremovaloflinksandvertices.Thesearesomedifferenttypesofgraphs:
DirectedgraphNon-directedgraphConnectedgraphNon-connectedgraphSimplegraphMulti-graph
Anadjacencylistconsistsofadjacentverticesofagraphthathaveobjectsorrecords.Anadjacencymatrixconsistsofsourceanddestinationvertices.Anincidencematrixisatwo-dimensionalBooleanmatrix.Thematrixhasrowsofverticesandcolumnsthatrepresentthelinks(edges).Networkrepresentationusingagraph isshowninthefollowingcode.Asocialgraphconsistsofanarrayoflinks:
///mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain
//importingfmtpackageimport("fmt")//SocialGraphtypeSocialGraphstruct{SizeintLinks[][]Link}
TheLinkstructisdefinedandimplementedinthenextsection.
![Page 450: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/450.jpg)
TheLinkclassTheLinkclassconsistsofthevertex1andvertex2vertices andtheLinkWeightintegerproperty:
//LinkclasstypeLinkstruct{Vertex1intVertex2intLinkWeightint}
Thenextsectiontalksaboutthe implementationofthedifferentLinkclassmethods.
![Page 451: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/451.jpg)
TheNewSocialGraphmethod
TheNewSocialGraphfunctioncreatesasocialgraphgivennum,whichisthesizeofthegraph.Sizeisthenumberoflinksinthegraph:
//NewSocialGraphmethodfuncNewSocialGraph(numint)*SocialGraph{return&SocialGraph{Size:num,Links:make([][]Link,num),}}
![Page 452: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/452.jpg)
TheAddLinkmethod
TheAddLinkmethodaddsthelinkbetweentwovertices.The AddLinkmethodofasocialgraphtakesvertex1,vertex2,andweightasparameters.Themethodaddsthelinkfromvertex1tovertex2,asshowninthefollowingcode:
//AddLinkmethodfunc(socialGraph*SocialGraph)AddLink(vertex1int,vertex2int,weightint){socialGraph.Links[vertex1]=append(socialGraph.Links[vertex1],Link{Vertex1:vertex1,Vertex2:vertex2,LinkWeight:weight})}
![Page 453: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/453.jpg)
ThePrintLinksmethod
ThePrintLinksmethodoftheSocialGraphclassprintsthelinksfromvertex=0andallthelinksinthegraph:
//PrintLinksExamplefunc(socialGraph*SocialGraph)PrintLinks(){
varvertexintvertex=0
fmt.Printf("Printingalllinksfrom%d\n",vertex)varlinkLinkfor_,link=rangesocialGraph.Links[vertex]{fmt.Printf("Link:%d->%d(%d)\n",link.Vertex1,link.Vertex2,link.LinkWeight)}
fmt.Println("Printingalllinksingraph.")varadjacent[]Linkfor_,adjacent=rangesocialGraph.Links{for_,link=rangeadjacent{fmt.Printf("Link:%d->%d(%d)\n",link.Vertex1,link.Vertex2,link.LinkWeight)}}}
![Page 454: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/454.jpg)
Themainmethod
ThemainmethodcreatesasocialgraphbyinvokingtheNewSocialGraphmethod.Thelinksfrom0to1,0to2,1to3,and2to4areaddedtothesocialgraph.ThelinksareprintedusingtheprintLinksmethod:
//mainmethodfuncmain(){
varsocialGraph*SocialGraph
socialGraph=NewSocialGraph(4)
socialGraph.AddLink(0,1,1)socialGraph.AddLink(0,2,1)socialGraph.AddLink(1,3,1)socialGraph.AddLink(2,4,1)
socialGraph.PrintLinks()
}
Runthefollowingcommandtoexecutethesocial_graph.gofile:gorunsocial_graph.go
Theoutputisasfollows:
Inthenextsection,wewilltakealookattheunittestforthesocialgraph
![Page 455: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/455.jpg)
Inthenextsection,wewilltakealookattheunittestforthesocialgraph
method.
TestHere,wehavewrittenaunittestforthesocialgraphmethod.Thecodeisasfollows:
///mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain
//importingtestingpackageimport("fmt""testing")//NewSocialGraphtestmethodfuncTestNewSocialGraph(test*testing.T){
varsocialGraph*SocialGraph
socialGraph=NewSocialGraph(1)
ifsocialGraph==nil{
test.Errorf("errorincreatingasocialGraph")}
}
Runthefollowingcommandtoexecutetheprecedingcodesnippet:gotest-runNewSocialGraph-v
Theoutputisasfollows:
![Page 456: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/456.jpg)
Inthenextsection, asocialnetworkrepresentation willbeimplementedwithcodeexamples.Theprecedinggraphwillbeenhancedwithnodes.Eachnodewillrepresentasocialentity.
![Page 457: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/457.jpg)
RepresentingasocialnetworkAsocialnetworkconsistsofsociallinksthatcontainsocialentitiessuchaspeople,friends,discussions,shares,beliefs,trust,andlikes.Thisgraphisusedtorepresentthesocialnetwork.Metrics relatedtotheproximityofentities canbecalculatedbasedonthegraph. Socialgraphsconsistofgraphnodesandlinks,whicharemapswithakeynameandmultiplekeysnames,respectively:
///Mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain
//importingfmtpackageimport("fmt")
typeNamestring
typeSocialGraphstruct{GraphNodesmap[Name]struct{}Linksmap[Name]map[Name]struct{}}
Thedifferentsocialnetworkmethodsareexplainedandimplementedinthenextsection.
![Page 458: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/458.jpg)
TheNewSocialGraphmethod
The NewSocialGraph methodreturnsasocialgraphconsistingof nil-valuedGraphNodesandLinks:
//NewSocialGraphmethodfuncNewSocialGraph()*SocialGraph{return&SocialGraph{GraphNodes:make(map[Name]struct{}),Links:make(map[Name]map[Name]struct{}),}}
![Page 459: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/459.jpg)
TheAddEntitymethod
TheAddEntitymethodaddstheentitytothesocialgraph.The AddEntitymethodofthe SocialGraphclasstakesnameasaparameterandreturnstrueifitisaddedtothesocialgraph:
//AddEntitymethodfunc(socialGraph*SocialGraph)AddEntity(nameName)bool{
varexistsboolif_,exists=socialGraph.GraphNodes[name];exists{returntrue}socialGraph.GraphNodes[name]=struct{}{}returntrue}
![Page 460: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/460.jpg)
TheAddLinkmethod
TheAddLinkmethodoftheSocialGraphclasstakesname1andname2 as parameters.Thismethodcreatestheentitiesifthenamedentitiesdonotexistandcreatesalinkbetweentheentities:
//AddLinkfunc(socialGraph*SocialGraph)AddLink(name1Name,name2Name){varexistsboolif_,exists=socialGraph.GraphNodes[name1];!exists{socialGraph.AddEntity(name1)}if_,exists=socialGraph.GraphNodes[name2];!exists{socialGraph.AddEntity(name2)}if_,exists=socialGraph.Links[name1];!exists{socialGraph.Links[name1]=make(map[Name]struct{})}socialGraph.Links[name1][name2]=struct{}{}}
![Page 461: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/461.jpg)
ThePrintLinksmethod
ThePrintLinksmethodoftheSocialGraphclassprintsthelinksadjacenttotheroot andallthelinks,asshowninthefollowingcodesnippet:
func(socialGraph*SocialGraph)PrintLinks(){varrootNameroot=Name("Root")
fmt.Printf("Printingalllinksadjacentto%d\n",root)
varnodeNamefornode=rangesocialGraph.Links[root]{//Edgeexistsfromutov.fmt.Printf("Link:%d->%d\n",root,node)}
varmmap[Name]struct{}fmt.Println("Printingalllinks.")forroot,m=rangesocialGraph.Links{varvertexNameforvertex=rangem{//Edgeexistsfromutov.fmt.Printf("Link:%d->%d\n",root,vertex)}}}
![Page 462: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/462.jpg)
Themainmethod
Themainmethodcreatesasocialgraph.Theentities,suchasjohn,per,andcynthia,arecreatedandlinkedwiththerootnode.Thefriends,suchasmayo,lorrie,andellie,arecreatedandlinkedwithjohnandper:
//mainmethodfuncmain(){
varsocialGraph*SocialGraph
socialGraph=NewSocialGraph()
varrootName=Name("Root")varjohnName=Name("JohnSmith")varperName=Name("PerJambeck")varcynthiaName=Name("CynthiaGibas")
socialGraph.AddEntity(root)socialGraph.AddEntity(john)socialGraph.AddEntity(per)socialGraph.AddEntity(cynthia)
socialGraph.AddLink(root,john)socialGraph.AddLink(root,per)socialGraph.AddLink(root,cynthia)
varmayoName=Name("MayoSmith")varlorrieName=Name("LorrieJambeck")varellieName=Name("EllieVlocksen")
socialGraph.AddLink(john,mayo)socialGraph.AddLink(john,lorrie)socialGraph.AddLink(per,ellie)
socialGraph.PrintLinks()}
Runthefollowingcommandtoexecutethesocial_graph_example.gofile:gorunsocial_graph_example.go
![Page 463: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/463.jpg)
Theoutputisasfollows:
Thenextsectiontalksaboutthemaplayoutimplementation.
![Page 464: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/464.jpg)
MaplayoutsAmaplayoutisageographicalvisualizationoflocationsthatarelinkedtogether.Thenodesinthegraphofamapconsistofgeo-basedinformation.Thenodewillhaveinformationsuchasthenameofthelocation,latitude,andlongitude.Mapsarelaidoutindifferentscales.Cartographicdesignisreferredtoasmapcreationusinggeographicinformation.Amaplayoutisshowninthefollowingcodesnippet.ThePlaceclassconsistsofName,Latitude,andLongitudeproperties:
///mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain
//importingfmtpackageimport("fmt")
//PlaceclasstypePlacestruct{
NamestringLatitudefloat64Longitudefloat64
}
ThenextsectiontalksabouttheMapLayout class.
![Page 465: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/465.jpg)
TheMapLayoutclassTheMapLayoutclassconsistsofGraphNodesandLinks:
//MapLayoutclasstypeMapLayoutstruct{GraphNodesmap[Place]struct{}Linksmap[Place]map[Place]struct{}}
ThedifferentMapLayoutmethodsareexplainedandimplementedinthenextsection.
![Page 466: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/466.jpg)
TheNewMapLayoutmethod
TheNewMapLayoutmethodcreatesaMapLayout.TheMapLayouthasGraphNodesandlinksmaps:
//NewMapLayoutmethodfuncNewMapLayout()*MapLayout{return&MapLayout{GraphNodes:make(map[Place]struct{}),Links:make(map[Place]map[Place]struct{}),}}
![Page 467: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/467.jpg)
TheAddPlacemethod
TheAddPlacemethodoftheMapLayoutclasstakesplace asa parameterandreturnstrueiftheplaceexists.Iftheplacedoesnotexist,thenagraphnodewithanewplacekeyiscreated:
//AddPlacemethodfunc(mapLayout*MapLayout)AddPlace(placePlace)bool{
varexistsboolif_,exists=mapLayout.GraphNodes[place];exists{returntrue}mapLayout.GraphNodes[place]=struct{}{}returntrue}
![Page 468: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/468.jpg)
TheAddLinkmethod
TheAddLinkmethodoftheMapLayoutclasstakestheplacesasparametersandlinksthemtogether:
//AddLinkfunc(mapLayout*MapLayout)AddLink(place1Place,place2Place){varexistsboolif_,exists=mapLayout.GraphNodes[place1];!exists{mapLayout.AddPlace(place1)}if_,exists=mapLayout.GraphNodes[place2];!exists{mapLayout.AddPlace(place2)}
if_,exists=mapLayout.Links[place1];!exists{mapLayout.Links[place1]=make(map[Place]struct{})}mapLayout.Links[place1][place2]=struct{}{}
}
![Page 469: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/469.jpg)
ThePrintLinksmethod
ThePrintLinksmethodofMapLayoutprintstheplacesandthelinks://PrintLinksmethodfunc(mapLayout*MapLayout)PrintLinks(){varrootPlaceroot=Place{"Algeria",3,28}
fmt.Printf("Printingalllinksadjacentto%s\n",root.Name)
varnodePlacefornode=rangemapLayout.Links[root]{fmt.Printf("Link:%s->%s\n",root.Name,node.Name)}
varmmap[Place]struct{}fmt.Println("Printingalllinks.")forroot,m=rangemapLayout.Links{varvertexPlaceforvertex=rangem{fmt.Printf("Link:%s->%s\n",root.Name,vertex.Name)}}}
![Page 470: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/470.jpg)
Themainmethod
Inthemainmethod,themaplayoutiscreatedbyinvokingtheNewMapLayoutmethod.Placesareinstantiatedandaddedtothemaplayout.Then,thelinksareaddedbetweenplaces:
//mainmethodfuncmain(){
varmapLayout*MapLayout
mapLayout=NewMapLayout()
varrootPlace=Place{"Algeria",3,28}varnetherlandsPlace=Place{"Netherlands",5.75,52.5}
varkoreaPlace=Place{"Korea",124.1,-8.36}vartunisiaPlace=Place{"Tunisia",9,34}
mapLayout.AddPlace(root)mapLayout.AddPlace(netherlands)mapLayout.AddPlace(korea)mapLayout.AddPlace(tunisia)
mapLayout.AddLink(root,netherlands)mapLayout.AddLink(root,korea)mapLayout.AddLink(root,tunisia)
varsingaporePlace=Place{"Singapore",103.8,1.36}varuaePlace=Place{"UAE",54,24}varjapanPlace=Place{"Japan",139.75,35.68}
mapLayout.AddLink(korea,singapore)mapLayout.AddLink(korea,japan)mapLayout.AddLink(netherlands,uae)
mapLayout.PrintLinks()}
![Page 471: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/471.jpg)
Runthefollowingcommandtoexecutethemap_layout.gofile:gorunmap_layout.go
Theoutputisasfollows:
Inthenextsection,wewilltakealookattheunittestfortheNewMapLayoutmethod.
![Page 472: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/472.jpg)
TestAunittestfortheMapLayoutclass'sNewMapLayoutmethod isshowninthefollowingcodesnippet:
///mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain
//importingtestingpackageimport("testing")
//NewMapLayouttestmethodfuncTestNewMapLayout(test*testing.T){
varmapLayout*MapLayout
mapLayout=NewMapLayout()
test.Log(mapLayout)
ifmapLayout==nil{
test.Errorf("errorincreatingamapLayout")}
}
Runthefollowingcommandtoexecutetheprecedingcodesnippet:gotest-runNewMapLayout-v
Theoutputisasfollows:
![Page 473: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/473.jpg)
Thenextsectiontalksaboutimplementinga knowledgegraph.
![Page 474: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/474.jpg)
KnowledgegraphsAknowledgegraphisanetworkrepresentationofentities,items,andusersasnodes.Thenodesinteractwithoneanothervialinksoredges.Knowledgegraphsarewidelyusedbecausetheyareschemaless.Thesedatastructuresareusedtorepresentknowledgeintheformofgraphs,andthenodeshavetextualinformation.Knowledgegraphsarecreatedbyusingitem,entity,andusernodesandlinkingthemwithedges.Anontologyconsistsofaknowledgegraphofinformationnodes.Thereasonerderivesknowledgefromknowledgegraphs.Aknowledgegraphconsistsofclasses,slots,andfacets,whichareontologicalterms. Inthefollowingcode,aknowledgegraphconsistingofacar'sbillofmaterialsisexplained.The Class typeconsistsofaname,whichisastring:
///mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain
//importingfmtpackageimport("fmt")
//ClassTypetypeClassstruct{Namestring}
Thenextsectiontalksabouttheknowledgegraph class.
![Page 475: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/475.jpg)
TheKnowledgeGraphclassTheKnowledgeGraphclassconsistsofGraphNodesandlinks:
//KnowledgeGraphtypetypeKnowledgeGraphstruct{GraphNodesmap[Class]struct{}Linksmap[Class]map[Class]struct{}}
Thedifferentknowledgegraphmethodsareexplainedandimplementedinthefollowingsections.
![Page 476: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/476.jpg)
TheNewKnowledgeGraphmethod
TheNewKnowledgeGraphmethodcreatesaknowledgegraph,whichconsistsofGraphNodesandLinksmaps:
//NewKnowledgeGraphmethodfuncNewKnowledgeGraph()*KnowledgeGraph{return&KnowledgeGraph{GraphNodes:make(map[Class]struct{}),Links:make(map[Class]map[Class]struct{}),}}
![Page 477: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/477.jpg)
TheAddClassmethod
TheAddClassmethodoftheKnowledgeGraphclasstakesclassasaparameter andreturnstrueiftheclassexists.Iftheclassdoesnotexist,aGraphNodeiscreatedwithclassasakey:
//AddClassmethodfunc(knowledgeGraph*KnowledgeGraph)AddClass(classClass)bool{
varexistsboolif_,exists=knowledgeGraph.GraphNodes[class];exists{returntrue}knowledgeGraph.GraphNodes[class]=struct{}{}returntrue}
![Page 478: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/478.jpg)
TheAddLinkmethod
TheAddLinkmethodoftheKnowledgeGraphclasstakesclass1andclass2 as parameters,andalinkiscreatedbetweentheseclasses:
//AddLinkfunc(knowledgeGraph*KnowledgeGraph)AddLink(class1Class,class2Class){varexistsboolif_,exists=knowledgeGraph.GraphNodes[class1];!exists{knowledgeGraph.AddClass(class1)}if_,exists=knowledgeGraph.GraphNodes[class2];!exists{knowledgeGraph.AddClass(class2)}
if_,exists=knowledgeGraph.Links[class1];!exists{knowledgeGraph.Links[class1]=make(map[Class]struct{})}knowledgeGraph.Links[class1][class2]=struct{}{}
}
![Page 479: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/479.jpg)
ThePrintLinksmethod
ThePrintLinksmethodoftheKnowledgeGraphclassprintsthelinksandnodes:
//PrintLinksmethodfunc(knowledgeGraph*KnowledgeGraph)PrintLinks(){varcarClasscar=Class{"Car"}
fmt.Printf("Printingalllinksadjacentto%s\n",car.Name)
varnodeClassfornode=rangeknowledgeGraph.Links[car]{fmt.Printf("Link:%s->%s\n",car.Name,node.Name)}
varmmap[Class]struct{}fmt.Println("Printingalllinks.")forcar,m=rangeknowledgeGraph.Links{varvertexClassforvertex=rangem{fmt.Printf("Link:%s->%s\n",car.Name,vertex.Name)}}}
![Page 480: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/480.jpg)
Themainmethod
Themainmethodcreatestheknowledgegraph,andtheclassesareinstantiated.Thelinksbetweentheclassesarecreatedandprinted:
//mainmethodfuncmain(){
varknowledgeGraph*KnowledgeGraph
knowledgeGraph=NewKnowledgeGraph()
varcar=Class{"Car"}vartyre=Class{"Tyre"}vardoor=Class{"Door"}varhood=Class{"Hood"}
knowledgeGraph.AddClass(car)knowledgeGraph.AddClass(tyre)knowledgeGraph.AddClass(door)knowledgeGraph.AddClass(hood)
knowledgeGraph.AddLink(car,tyre)knowledgeGraph.AddLink(car,door)knowledgeGraph.AddLink(car,hood)
vartube=Class{"Tube"}varaxle=Class{"Axle"}varhandle=Class{"Handle"}varwindowGlass=Class{"WindowGlass"}
knowledgeGraph.AddClass(tube)knowledgeGraph.AddClass(axle)knowledgeGraph.AddClass(handle)knowledgeGraph.AddClass(windowGlass)
knowledgeGraph.AddLink(tyre,tube)knowledgeGraph.AddLink(tyre,axle)knowledgeGraph.AddLink(door,handle)knowledgeGraph.AddLink(door,windowGlass)
knowledgeGraph.PrintLinks()}
Runthefollowingcommandtoexecutethe knowledge_catalog.gofile:
![Page 481: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/481.jpg)
gorunknowledge_catalog.go
Theoutputisasfollows:
Inthenextsection,wewilltakealookattheunittestfortheNewKnowledgeGraphmethod.
![Page 482: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/482.jpg)
TestTheNewKnowledgeGraphmethodisunittestedinthefollowingcodesnippet:
///mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain
//importingtestingpackageimport("testing")
//NewKnowledgeGraphtestmethodfuncTestNewKnowledgeGraph(test*testing.T){
varknowledgeGraph*KnowledgeGraph
knowledgeGraph=NewKnowledgeGraph()
test.Log(knowledgeGraph)
ifknowledgeGraph==nil{
test.Errorf("errorincreatingaknowledgeGraph")}
}
Runthefollowingcommandtoexecutetheprecedingcodesnippet:gotest-runNewKnowledgeGraph-v
Theoutputisasfollows:
![Page 483: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/483.jpg)
Thenextsectiontalksabouttherepresentationofthe sparsematrix.
![Page 484: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/484.jpg)
SparsematrixrepresentationusingalistoflistsAsparsematrixisatwo-dimensionallistofmrowsandncolumns.Theshapeofamatrixismxnifitconsistsofmrowsandncolumns.Sparsematricesareusedforsolvinglarge-scaleproblemsthatdonotrequiredensematrices.Forexample,partialdifferentialequationsaresolvedbyusingthe finiteelementmethod(FEM).Tuplesofasparsematrixarenon-zeroelementsofthematrix.Inthefollowingcode,asparsematrixismodeledasalistoflists.Asparsematrixconsistsofcellsthatarealistoflists.EachcellhaspropertiessuchasRow,Column,andValue:
///mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain
//importingfmtpackageimport("fmt")
//ListofListtypeLOLstruct{RowintColumnintValuefloat64}
ThenextsectiontalksabouttheSparseMatrixclass.
![Page 485: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/485.jpg)
SparseMatrixclassSparseMatrixhasacellsarrayandshape,whichisanintegerarray:
//SparseMatrixtypeSparseMatrixstruct{cells[]LOLshape[2]int}
Inthenextsection,thedifferentSparsemethodsofthe SparseMatrixstructareimplemented.
![Page 486: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/486.jpg)
TheShapemethod
TheShapemethodoftheSparseMatrixclassreturnstheshapearrayelements:
//Shapemethodfunc(sparseMatrix*SparseMatrix)Shape()(int,int){returnsparseMatrix.shape[0],sparseMatrix.shape[1]}
![Page 487: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/487.jpg)
TheNumNonZeromethod
TheNumNonZeromethodfindsthecellswithnon-zeroelements.The NumNonZeromethodoftheSparseMatrixclassreturnsthesizeofthecellsarrayinsparseMatrix:
//NumNonZeromethodfunc(sparseMatrix*SparseMatrix)NumNonZero()int{returnlen(sparseMatrix.cells)}
![Page 488: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/488.jpg)
TheLessThanmethod
TheLessThanmethodcomparesthelistoflistsrowsandcolumnsandcheckswhethertherowislessthaniandthatthecolumnislessthanj:
//LessThanmethodfuncLessThan(lolLOL,iint,jint)bool{
iflol.Row<i&&lol.Column<j{
returntrue}
returnfalse}
![Page 489: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/489.jpg)
TheEqualmethod
TheEqualmethodcheckswhetherthelistoflistsrowsandcolumnsareequaltoiandj,respectively:
//EqualmethodfuncEqual(lolLOL,iint,jint)bool{iflol.Row==i&&lol.Column==j{returntrue}returnfalse}
![Page 490: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/490.jpg)
TheGetValuemethod
TheGetValuemethodoftheSparseMatrixclassreturnsthevalueofthecellwhoserowandcolumnequaliandj,respectively:
//GetValuemethodfunc(sparseMatrix*SparseMatrix)GetValue(iint,jint)float64{varlolLOLfor_,lol=rangesparseMatrix.cells{ifLessThan(lol,i,j){continue}ifEqual(lol,i,j){returnlol.Value}return0.0}return0.0}
![Page 491: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/491.jpg)
TheSetValuemethod
TheSetValuemethodoftheSparseMatrixclasssetsthevalueofthecellwiththerowandcolumnequaltoiandj,respectively,astheparametervalue:
//SetValuemethodfunc(sparseMatrix*SparseMatrix)SetValue(iint,jint,valuefloat64){
varlolLOLvarindexintforindex,lol=rangesparseMatrix.cells{ifLessThan(lol,i,j){continue}ifEqual(lol,i,j){sparseMatrix.cells[index].Value=valuereturn}
sparseMatrix.cells=append(sparseMatrix.cells,LOL{})varkintfork=len(sparseMatrix.cells)-2;k>=index;k--{sparseMatrix.cells[k+1]=sparseMatrix.cells[k]}sparseMatrix.cells[index]=LOL{Row:i,Column:j,Value:value,}return}sparseMatrix.cells=append(sparseMatrix.cells,LOL{Row:i,Column:j,Value:value,})}
![Page 492: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/492.jpg)
TheNewSparseMatrixmethod
TheNewSparseMatrixmethodtakesthemandnasparameters andreturnstheinitializedmatrix:
//NewSparseMatrixmethodfuncNewSparseMatrix(mint,nint)*SparseMatrix{return&SparseMatrix{cells:[]LOL{},shape:[2]int{m,n},}}
![Page 493: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/493.jpg)
Themainmethod
ThemainmethodcreatesthesparsematrixbyinvokingtheNewSparseMatrixmethod.Thevaluesaresetincells(1,1)and(1,3).Thesparsematrixandthenumberofnon-zerocellsareprinted:
//mainmethodfuncmain(){
varsparseMatrix*SparseMatrix
sparseMatrix=NewSparseMatrix(3,3)
sparseMatrix.SetValue(1,1,2.0)sparseMatrix.SetValue(1,3,3.0)
fmt.Println(sparseMatrix)fmt.Println(sparseMatrix.NumNonZero())}
Runthefollowingcommandtoexecutethesparse_matrix.gofile:gorunsparse_matrix.go
Theoutputisasfollows:
![Page 494: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/494.jpg)
SummaryThischaptercoveredhowtopresentnetworksandsparsematricesusinggraphsandalistoflists,respectively. Socialnetworkrepresentation,maplayouts,andknowledgegraphswerediscussedindetailwithcodeexamples.Thedifferentsparsematrixmethodswerealsoimplementedwiththeappropriatecode.Inthenextchapter,algorithmssuchasgarbagecollection,cachemanagement,andspaceallocationwillbepresentedwithcodeexamplesandanefficiencyanalysis.
![Page 495: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/495.jpg)
QuestionsWhatdatastructureisusedtorepresentasetoflinkedobjects?Whatisatwo-dimensionalmatrixwithBooleanvaluescalled?Giveacodeexampleforanetworkrepresentationusingagraph.Whichmetricscanbecalculatedfromasocialgraph?Whatisacartographicdesign?Giveanexampleofaknowledgegraphanddefinetheclass,slots,andfacets.Whataretheapplicationsofsparsematrices?Definealistoflistsandwriteacodesample.Whatisamaplayout?Whatdifferentoperationscanbeperformedusinggraphs?
![Page 496: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/496.jpg)
Furtherreading
Thefollowingbooksarerecommendedifyouwanttoknowmoreaboutgraphsandlistoflists:
DesignPatterns, byErichGamma,RichardHelm,RalphJohnson,andJohnVlissidesIntroductiontoAlgorithms –ThirdEdition,byThomasH.Cormen,CharlesE.Leiserson,RonaldL.Rivest,andCliffordSteinDatastructuresandAlgorithms:AnEasyIntroduction,by RudolphRussell
![Page 497: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/497.jpg)
MemoryManagementMemorymanagementisawaytocontrolandorganizememory.Memorydivisionsarecalledblocks,andtheyareusedforrunning differentprocesses.Thebasicgoalofmemorymanagementalgorithmsistodynamicallydesignatesegmentsofmemorytoprogramsondemand.Thealgorithmsfreeupmemoryforreusewhentheobjectsinthememoryareneverrequiredagain.Garbagecollection,cachemanagement,andspaceallocationalgorithmsaregoodexamplesofmemorymanagementtechniques.Insoftwareengineering,garbagecollectionisusedtofreeupmemorythat'sbeenallocatedtothoseobjectsthatwon'tbeusedagain,thushelpinginmemorymanagement. Thecacheprovidesin-memorystoragefordata.Youcansortthedatainthecacheintolocale-specificgroups.Thedatacanbestoredusingkeyandvaluesets.Thischaptercoversthegarbagecollection,cachemanagement,andspaceallocationalgorithms.Thememorymanagementalgorithmsarepresentedwithcodesamplesandefficiencyanalyses.Thefollowingtopicswillbecoveredinthischapter:
GarbagecollectionCachemanagementSpaceallocationConcepts—Gomemorymanagement
We'lllookatgarbagecollectionfirst,thenlookatthedifferentalgorithmsrelatedtogarbagecollection.
![Page 498: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/498.jpg)
TechnicalrequirementsInstallGoVersion1.10fromGolang(https://golang.org/),choosingtherightversionforyourOS.TheGitHubrepositoryforthecodeinthischaptercanbefoundhere: https://github.com/PacktPublishing/Learn-Data-Structures-and-Algorithms-with-Golang/tree/master/Chapter10.
![Page 499: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/499.jpg)
Garbagecollection
Garbagecollectionisatypeofprogrammedmemorymanagementinwhichmemory,currentlyoccupiedbyobjectsthatwillneverbeusedagain,isgathered.JohnMcCarthywasthefirstpersontocomeupwithgarbagecollectionformanagingLispmemorymanagement.Thistechniquespecifieswhichobjectsneedtobede-allocated,andthendischargesthememory.Thestrategiesthatareutilizedforgarbagecollectionarestackallocationandregioninterference.Sockets,relationaldatabasehandles,userwindowobjects,andfileresourcesarenotoverseenbygarbagecollectors.Garbagecollectionalgorithmshelpreducedanglingpointerdefects,double-freedefects,andmemoryleaks.Thesealgorithmsarecomputing-intensiveandcausedecreasedorunevenperformance.AccordingtoApple,oneofthereasonsforiOSnothavinggarbagecollectionisthatgarbagecollectionneedsfivetimesthememorytomatchexplicitmemorymanagement.Inhigh-transactionalsystems,concurrent,incremental,andreal-timegarbagecollectorshelpmanagememorycollectionandrelease.Garbagecollectionalgorithmsdependonvariousfactors:
GCthroughputHeapoverheadPausetimesPausefrequencyPausedistributionAllocationperformanceCompactionConcurrencyScalingTuningWarm-uptimePagereleasePortabilityCompatibility
That'ssimple,deferred,one-bit,weightedreferencecounting,mark-and-sweep,andgenerationalcollectionalgorithmsdiscussedinthefollowingsections.
![Page 500: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/500.jpg)
TheReferenceCounterclassThefollowingcodesnippetshowshowreferencestocreated objectsaremaintainedinthestack.TheReferenceCounterclasshasthenumberofreferences,includingthepoolofreferencesandremovedreferences,asproperties:
//mainpackagehasexamplesshown//inHands-OnDataStructuresandalgorithmswithGobookpackagemain
//importingfmtpackageimport("fmt""sync")
//ReferenceCountertypeReferenceCounterstruct{num*uint32pool*sync.Poolremoved*uint32}
Let'stakealookatthemethodoftheReferenceCounterclass.
![Page 501: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/501.jpg)
ThenewReferenceCountermethod
ThenewReferenceCountermethodinitializesaReferenceCounterinstanceandreturnsapointertoReferenceCounter.Thisisshowninthefollowingcode:
//newReferenceCountermethodfuncnewReferenceCounter()*ReferenceCounter{return&ReferenceCounter{num:new(uint32),pool:&sync.Pool{},removed:new(uint32),}}
TheStackclassisdescribedinthenextsection.
![Page 502: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/502.jpg)
TheStackclassTheStackclassconsistsofareferencesarrayandCountasproperties.Thisisshowninthefollowingcode:
//StackclasstypeStackstruct{references[]*ReferenceCounterCountint}
Let'stakealookatthemethodsofthe Stackclass.
![Page 503: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/503.jpg)
TheStackclass–anewmethod
Now,let'slookattheheapinterfacemethodsthatareimplementedbytheStackclass.Thenewmethodinitializesthereferencesarray,andthe PushandPop heapinterfacemethodstakethereferenceparameter topushandpopreferenceoutofthestack.Thisisshowninthefollowingcode:
//NewmethodofStackClassfunc(stack*Stack)New(){stack.references=make([]*ReferenceCounter,0)}
//Pushmethodfunc(stack*Stack)Push(reference*ReferenceCounter){stack.references=append(stack.references[:stack.Count],reference)stack.Count=stack.Count+1}
//Popmethodfunc(stack*Stack)Pop()*ReferenceCounter{ifstack.Count==0{returnnil}varlengthint=len(stack.references)varreference*ReferenceCounter=stack.references[length-1]iflength>1{stack.references=stack.references[:length-1]}else{stack.references=stack.references[0:]}stack.Count=len(stack.references)returnreference}
![Page 504: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/504.jpg)
Themainmethod
Inthefollowingcodesnippet,let'sseehowStackisused.AStack instanceisinitialized,andreferencesareaddedtothestackbyinvokingthePushmethod.ThePopmethodisinvokedandtheoutputisprinted:
//mainmethodfuncmain(){varstack*Stack=&Stack{}stack.New()varreference1*ReferenceCounter=newReferenceCounter()varreference2*ReferenceCounter=newReferenceCounter()varreference3*ReferenceCounter=newReferenceCounter()varreference4*ReferenceCounter=newReferenceCounter()stack.Push(reference1)stack.Push(reference2)stack.Push(reference3)stack.Push(reference4)fmt.Println(stack.Pop(),stack.Pop(),stack.Pop(),stack.Pop())}
Runthefollowingcommandstoexecutethestack_garbage_collection.gofile:
gorunstack_garbage_collection.go
Theoutputisasfollows:
Thereferencecounting,mark-and-sweep,andgenerationalcollectionalgorithmswillbediscussedinthefollowingsections.
![Page 505: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/505.jpg)
Referencecounting
Referencecountingisatechniquethat'susedforkeepingthecountofreferences,pointers,andhandlestoresources.Memoryblocks,diskspace,andobjectsaregoodexamplesofresources.Thistechniquetrackseachobjectasaresource.Themetricsthataretrackedarethenumberofreferencesheldbydifferentobjects.Theobjectsarerecoveredwhentheycanneverbereferenced again.Thenumberofreferencesisusedforruntimeoptimizations.Deutsch-Bobrowcameupwiththestrategyofreferencecounting.Thisstrategywasrelatedtothenumberofupdatedreferencesthatwereproducedbyreferencesthatwereputinlocalvariables.HenryBakercameupwithamethodthatincludesreferencesinlocalvariablesthataredeferreduntilneeded.Inthefollowingsubsections,thesimple,deferred,one-bit,andweightedtechniquesofreferencecountingwillbediscussed.
![Page 506: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/506.jpg)
Simplereferencecounting
Referencecountingisrelatedto keepingthenumberofreferences,pointers,andhandlestoaresourcesuchasanobject,blockofmemory,ordiskspace.Thistechniqueisrelatedtothenumberofreferencestode-allocatedobjectsthatareneverreferencedagain.Thecollectiontechniquetracks,foreachobject,atallyofthenumberofreferencestotheobject. Thereferencesareheldbyotherobjects.Theobjectgetsremovedwhenthenumberofreferences totheobjectiszero.Theremovedobjectbecomesinaccessible. Theremovalof areferencecanpromptcountlessconnectedreferencestobepurged. Thealgorithmistime-consumingbecauseofthesizeoftheobjectgraphandslowaccessspeed. Inthefollowingcodesnippets,wecanseeasimplereference-countingalgorithmbeingimplemented.The ReferenceCounterclasshasnumber(num),pool,andremovedreferencesasproperties:
///mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain
//importingsync,atomicandfmtpackagesimport("sync/atomic""sync""fmt")
//ReferenceCountertypeReferenceCounterstruct{num*uint32pool*sync.Poolremoved*uint32}
ThenewReferenceCounter,Add,andSubtractmethodsoftheReferenceCounterclassareshowninthefollowingsnippet:
//newReferenceCountermethodfuncnewReferenceCounter()ReferenceCounter{returnReferenceCounter{num:new(uint32),pool:&sync.Pool{},removed:new(uint32),}}
![Page 507: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/507.jpg)
//Addmethodfunc(referenceCounterReferenceCounter)Add(){atomic.AddUint32(referenceCounter.num,1)}
//Subtractmethodfunc(referenceCounterReferenceCounter)Subtract(){ifatomic.AddUint32(referenceCounter.num,^uint32(0))==0{atomic.AddUint32(referenceCounter.removed,1)}}
Let'slookatthemainmethodandseeanexampleofsimplereferencecounting.ThenewReferenceCountermethodisinvoked,andareferenceisaddedbyinvokingtheAddmethod.Thecount referenceisprintedattheend.Thisisshowninthefollowingcodesnippet
//mainmethodfuncmain(){varreferenceCounterReferenceCounterreferenceCounter=newReferenceCounter()referenceCounter.Add()fmt.Println(*referenceCounter.count)}
Runthefollowingcommandstoexecutethereference_counting.gofile:gorunreference_counting.go
Theoutputisasfollows:
Thedifferenttypesofreferencecountingtechniquesaredescribedinthefollowingsections.
![Page 508: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/508.jpg)
Deferredreferencecounting
Deferredreferencecountingisaprocedure inwhichreferencesfromdifferentobjectstoagivenobjectarecheckedandprogram-variablereferencesareoverlooked. Ifthetallyofthereferencesiszero,thatobjectwillnotbeconsidered.Thisalgorithmhelpsreducetheoverheadofkeepingcounts uptodate.Deferredreferencecountingissupportedbymanycompilers.
![Page 509: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/509.jpg)
One-bitreferencecounting
Theone-bitreferencecountingtechnique utilizesasolitarybitflagtoshowwhetheranobjecthasoneormorereferences. Theflagisstoredaspartoftheobjectpointer.Thereisnorequirement tospareanyobjectforextraspaceinthistechnique.Thistechniqueisviablesince themajorityofobjectshaveareferencecountof1.
![Page 510: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/510.jpg)
Weightedreferencecounting
Theweightedreferencecountingtechnique talliesthenumberofreferencestoanobject,andeachreferenceisdelegatedaweight.Thistechniquetracksthetotalweightofthereferencestoanobject. WeightedreferencecountingwasinventedbyBevan,Watson,andWatsonin1987.Thefollowingcodesnippetshowsanimplementationoftheweightedreferencecountingtechnique:
//ReferenceCountertypeReferenceCounterstruct{num*uint32pool*sync.Poolremoved*uint32weightint}
//WeightedReferencemethodfuncWeightedReference()int{varreferences[]ReferenceCounterreferences=GetReferences(root)varreferenceReferenceCountervarsumintfor_,reference=rangereferences{sum=sum+reference.weight}returnsum}
![Page 511: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/511.jpg)
Themark-and-sweepalgorithm
Themark-and-sweepalgorithmisbasedonanideathatwasproposedbyDijkstrain1978.Inthegarbagecollectionstyle,theheapconsistsofagraphofconnectedobjects,whicharewhite.Thistechniquevisitstheobjectsandcheckswhether theyarespecificallyavailablebytheapplication. Globalsandobjectsonthestackareshadedgrayinthistechnique.Everygrayobjectisdarkenedtoblackandfilteredforpointerstootherobjects. Anywhiteobjectfoundintheoutputisturnedgray.Thiscalculationisrehasheduntiltherearenograyobjects.Whiteobjectsthatareleftoutareinaccessible.Amutatorinthisalgorithmhandlesconcurrencybychangingthepointerswhilethecollectorisrunning.Italsotakescareoftheconditionsothatnoblackobjectpointstoawhiteobject.Themarkalgorithmhasthefollowingsteps:
1. Marktherootobject2. Marktherootbitastrueifthevalueofthebit isfalse3. Foreveryreferenceofroot,markthereference,asinthefirststep
Thefollowingcodesnippetshowsthemarkingalgorithm.Let'slookattheimplementationoftheMark method:
funcMark(root*object){varmarkedAlreadyboolmarkedAlready=IfMarked(root)if!markedAlready{map[root]=true}varreferences*object[]references=GetReferences(root)varreference*objectfor_,reference=rangereferences{Mark(reference)}}
Thesweepalgorithm'spseudocodeispresentedhere:Foreachobjectintheheap,markthebitasfalseifthevalueofthebitistrueIfthevalueofthebitistrue,releasetheobjectfromtheheap
Thesweepalgorithmreleasestheobjectsthataremarkedforgarbagecollection.Now,let'slookattheimplementationofthe sweepalgorithm:
funcSweep(){varobjects*[]object
![Page 512: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/512.jpg)
varobjects*[]object
objects=GetObjects()varobject*objectfor_,object=rangeobjects{varmarkedAlreadyboolmarkedAlready=IfMarked(object)ifmarkedAlready{map[object]=true}Release(object)}}
![Page 513: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/513.jpg)
Thegenerationalcollectionalgorithm
Thegenerationalcollectionalgorithmdividestheheapofobjectsintogenerations.Agenerationofobjectswillbeexpiredandcollectedbythealgorithmbasedontheirage.Thealgorithmpromotesobjectstooldergenerationsbasedontheageoftheobjectinthegarbagecollectioncycle.Theentireheapneedstobescavenged,evenifagenerationiscollected.Let'ssaygeneration3iscollected;inthiscase,generations0-2arealsoscavenged.Thegenerationalcollectionalgorithmispresentedinthefollowingcodesnippet:
funcGenerationCollect(){varcurrentGenerationintcurrentGeneration=3varobjects*[]objectobjects=GetObjectsFromOldGeneration(3)varobject*objectfor_,object=rangeobjects{varmarkedAlreadyboolmarkedAlready=IfMarked(object)ifmarkedAlready{map[object]=true}}}
We'lltakealookatcachemanagementinthenextsection.
![Page 514: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/514.jpg)
CachemanagementCachemanagementconsistsofmanagingstatic,dynamic,andvariableinformation:
StaticinformationneverchangesDynamicinformationchangesfrequentlyVariableinformationchangeslessfrequentlythandynamicinformation
Theobjectcacheisstoredinvariousdatastructures,suchasmapsandtrees.Mapshaveakeyasanidentifierandavalue,whichisanobject.Cacheobjectscanberelatedtomemory,disks,pools,andstreams.Cacheshaveattributesrelatedtotimetolive,group,andregion.Aregionconsistsofacollectionofmappedkey-values.Regionscanbeindependentofotherregions.Cacheconfigurationconsistsofdefaults,regions,andauxiliaries.Atypicalcachemanagerhasthefollowingfeatures:
MemorymanagementThreadpoolcontrolsGroupingofelementsConfigurableruntimeparametersRegiondataseparationandconfigurationRemotesynchronizationRemotestorerecoveryEventhandlingRemoteserverchainingandfailoverCustomeventloggingCustomeventqueueinjectionKeypattern-matchingretrievalNetwork-efficientmulti-keyretrieval
The CacheObjectclassandthe Cacheclassaredescribedinthefollowingsections.
![Page 515: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/515.jpg)
TheCacheObjectclassTheCacheObjectclasshasValueandTimeToLiveproperties.Thisisshowninthefollowingcode:
///mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain
//importingfmt,syncandtimepackagesimport("fmt""sync""time")
//CacheObjectclasstypeCacheObjectstruct{ValuestringTimeToLiveint64}
TheIfExpiredmethodoftheCacheObjectclassisshowninthenextsection.
![Page 516: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/516.jpg)
TheIfExpiredmethod
IfExpiredcheckswhetherthecacheobjecthasexpired.The IfExpiredmethodofCacheObjectreturnstrueifTimeToLivehasnotexpired;otherwise,itreturnsfalse.Thisisshowninthefollowingcode:
//IfExpiredmethodfunc(cacheObjectCacheObject)IfExpired()bool{ifcacheObject.TimeToLive==0{returnfalse}returntime.Now().UnixNano()>cacheObject.TimeToLive}
![Page 517: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/517.jpg)
TheCacheclassTheCacheclassconsistsof objectsmapwitha string key,aCacheObjectvalue, andasync.RWMutexmutex.Thisisshowninthefollowingcode:
//CacheclasstypeCachestruct{objectsmap[string]CacheObjectmutex*sync.RWMutex}
TheNewCache,GetObject,and SetValuemethodsoftheCacheclassareshowninthefollowingsections.
![Page 518: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/518.jpg)
TheNewCachemethod
TheNewCachemethodreturnsapointertoacache,whichisinitializedwiththe nilmap(thatis,amapwithoutvalues) andRWMutex.Thisisshowninthefollowingcode:
//NewCachemethodfuncNewCache()*Cache{return&Cache{objects:make(map[string]CacheObject),mutex:&sync.RWMutex{},}}
![Page 519: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/519.jpg)
TheGetObjectmethod
TheGetObject methodretrievestheobjectgiventhecachekey.The GetObjectmethodoftheCacheclassreturnsthevalueofcacheKey.TheRLockmethodonthemutexobjectofthecacheisinvoked,andtheRUnlockmethodisdeferredbeforereturningthevalueofcacheKey.Iftheobjecthasexpired,thekeyvaluewillbeanemptystring.Thisisshowninthefollowingcode:
//GetObjectmethodfunc(cacheCache)GetObject(cacheKeystring)string{cache.mutex.RLock()defercache.mutex.RUnlock()varobjectCacheObjectobject=cache.objects[cacheKey]ifobject.IfExpired(){delete(cache.objects,cacheKey)return""}returnobject.Value}
![Page 520: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/520.jpg)
TheSetValuemethod
TheSetValuemethodoftheCacheclasstakescacheKey,cacheValue,andtimeToLiveparameters.TheLockmethod onthemutexobjectofthecacheisinvoked,andtheUnlockmethodisdeferred.AnewCacheObjectiscreatedwithcacheValueandTimeToLiveasproperties.ThecreatedcacheObjectissetasavaluetomapobjectswiththecacheKeykey.Thisisshowninthefollowingcode:
//SetValuemethodfunc(cacheCache)SetValue(cacheKeystring,cacheValuestring,timeToLivetime.Duration){cache.mutex.Lock()defercache.mutex.Unlock()cache.objects[cacheKey]=CacheObject{Value:cacheValue,TimeToLive:time.Now().Add(timeToLive).UnixNano(),}}
We'llimplementthemethodswejusttookalookatinthemainmethodinthenextsection.
![Page 521: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/521.jpg)
Themainmethod
ThemainmethodcreatesthecachebyinvokingtheNewCachemethod.ThekeyandvaluearesetonthecachebyinvokingsetValue.ThevalueisaccessedbycallingtheGetObjectmethodoftheCacheclass.Thisisshowninthefollowingcode:
//mainmethodfuncmain(){varcache*Cachecache=NewCache()cache.SetValue("name","johnsmith",200000000)varnamestringname=cache.GetObject("name")fmt.Println(name)}
Runthefollowingcommandtoexecutethecache_management.gofile:goruncache_management.go
Theoutputisasfollows:
Thenextsectiontalksaboutthespaceallocationalgorithm.
![Page 522: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/522.jpg)
Spaceallocation
Eachfunctionhasstackframesassociatedwithindividualmemoryspace.Functionshaveaccesstothememory insidetheframe,andaframepointerpointstothememory'slocation.Transitionbetweenframesoccurswhenthefunctionisinvoked.Dataistransferredbyvaluefromoneframetoanotherduringthetransition.Stackframecreationandmemoryallocationisdemonstratedinthefollowingcode.The addOne functiontakesnumandincrementsitbyone.Thefunctionprintsthevalueandaddressofnum:
///mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain
//importingfmtpackageimport("fmt")
//incrementmethodfuncaddOne(numint){num++fmt.Println("addedtonum",num,"Addressofnum",&num)}
Themainmethodinitializesthevariablenumberas17.ThenumbervalueandaddressareprintedbeforeandafterinvokingtheaddOnefunction.Thisisshowninthefollowingcode:
//mainmethodfuncmain(){varnumberintnumber=17fmt.Println("valueofnumber",number,"Addressofnumber",&number)addOne(number)fmt.Println("valueofnumberafteraddingOne",number,"Addressof",&number)}
Runthefollowingcommandtoexecutethestack_memory_allocation.gofile:gorunstack_memory_allocation.go
Theoutputisasfollows:
![Page 523: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/523.jpg)
Framepointersareexplainedinthenextsection.
![Page 524: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/524.jpg)
PointersPointershaveanaddressthatis4or8byteslong,dependingonwhetheryouhavea32-bitor64-bitarchitecture.Thestack'smainframeconsistsofthenumber17withtheaddress0xc420016058.Afteraddingone,anewframewithnumequalto18andanaddressof0xc420016068iscreated.Themainmethodprintsthestack'smainframeafterinvokingtheaddOnefunction. Thecodeinthefollowingsectionsdemonstratesmemoryspaceallocationwithpointersinsteadofactualvaluespassedintoafunction.TheAddOneandmainmethodsofpointersareshowninthefollowingsections.
![Page 525: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/525.jpg)
TheaddOnemethod
The addOne functiontakesapointertonumandincrementsitby1.Thefunctionprintsthevalue,address,andpointerofnum.Thisisshowninthefollowingcode:
///mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain
//importingfmtpackageimport("fmt")
//incrementmethodfuncaddOne(num*int){*num++fmt.Println("addedtonum",num,"Addressofnum",&num,"ValuePointsTo",*num)}
![Page 526: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/526.jpg)
Themainmethod
Themainmethodinitializesthevariablenumberto17.ThepointertothenumberispassedtotheaddOnefunction.ThenumbervalueandaddressisprintedbeforeandafterinvokingtheaddOnefunction.Inthisexample,theaddressofthenumberisthesameasthe value of numintheaddOnefunction.Pointerssharetheaddressofthevariableforthefunctiontoaccessforreadsandwriteswithinthestackframe.Pointertypesarespecifictoeverytypethatisdeclared.Pointersprovideindirectmemoryaccessoutsidethefunction'sstackframe.Thisisshowninthefollowingcode:
//mainmethodfuncmain(){varnumberintnumber=17fmt.Println("valueofnumber",number,"Addressofnumber",&number)addOne(&number)fmt.Println("valueofnumberafteraddingOne",number,"Addressof",&number)}
Runthefollowingcommandtoexecutethestack_memory_pointer.gofile:gorunstack_memory_pointer.go
Theoutputisasfollows:
ThenextsectiontalksaboutmemorymanagementinGo.
![Page 527: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/527.jpg)
Concepts– GomemorymanagementInGo,programmersdon'tneedtoworryaboutcodingavariable'svalueplacementinmemoryandspaceallocation.GarbagecollectioninGoisoverseenbythememorymanager.TheGOGC variableisusedtosetavaluefortheinitialgarbagecollectiontargetpercentage.Garbagecollectionisactivatedwhentheproportionoffreshlyallotteddatatothelivedatathat remainsafterthepreviousgarbagecollection reachesthetargetpercentage.Thedefaultvalueofthe GOGCvariable is100.Thissettingcanbeturnedoff,whichstopsgarbagecollection. ThecurrentimplementationofgarbagecollectioninGousesthemark-and-sweepalgorithm.Someofthebestpracticesthatyoucanfollowtoimprovememorymanagementareasfollows:
SmallobjectscanbecombinedintolargerobjectsLocalvariablesthathaveescapedfromtheirdeclarationscopecanbepromotedintoheapallocationsSlicearraypre-allocationcanbeperformedtoimprovememoryUseint8,insteadofint,because int8isasmallerdatatypeObjectsthatdonothaveanypointerswillnotbescannedbythegarbagecollectorFreeListscanbeusedtoreusetransientobjectsandreducethenumberofallocations
![Page 528: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/528.jpg)
Profiling
ProfilinginGocanbeenabledbyusingthecpuprofile andmemprofileflags.TheGotestingpackagehassupportforbenchmarkingandprofiling.Thecpuprofileflagcanbeinvokedbythefollowingcommand:
gotest-run=none-bench=ClientServerParallel4-cpuprofile=cprofilenet/http
Thebenchmarkcanbewrittentoacprofileoutputfileusingthefollowingcommand:
gotoolpprof--texthttp.testcprof
Let'slookatanexampleofhowtoprofiletheprogramsthatyouhavewritten.Theflag.Parsemethodreadsthecommand-lineflags. TheCPUprofilingoutputiswrittentoafile.TheStopCPUProfilemethodontheprofileriscalledtoflushanypendingfileoutputthatneedstobewrittenbeforetheprogramstops:
varprofile=flag.String("cpuprofile","","cpuprofiletooutputfile")funcmain(){flag.Parse()if*profile!=""{varfile*os.Filevarerrerrorfile,err=os.Create(*profile)iferr!=nil{log.Fatal(err)}pprof.StartCPUProfile(file)deferpprof.StopCPUProfile()}
![Page 529: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/529.jpg)
SummaryThischaptercoveredthegarbagecollection,cachemanagement,andmemoryspaceallocationalgorithms.Welookedatreferencecountingalgorithms,includingsimple,deferred,one-bit,andweighted.Themark-and-sweepandgenerationalcollectionalgorithmswerealsopresentedwithcodeexamples. Thenextchapterwillcoverthenextstepswecantakeaftergoingthroughthisbook.
![Page 530: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/530.jpg)
Questions1. Whichfactorsareconsideredwhenchoosingagarbagecollectionalgorithm?
2. Inwhichreferencecountingalgorithmareprogram-variablereferencesignored?
3. Whatisthetypeofreferencecountingalgorithminwhichasingle-bitflagisusedforcounting?
4. Inwhichreferencecountingalgorithmisaweightassignedtoeachreference?
5. Whoinventedweightedreferencecounting?6. WhichgarbagecollectionalgorithmwasproposedbyDijkstra?7. Whatclasshandlesconcurrencywhenthemark-and-sweepcollectorisrunning?
8. Whatarethecriteriaforpromotingobjectstooldergenerations?9. Drawaflowchartforthecachemanagementalgorithm.10. Howdoyougetindirectmemoryaccessoutsideamethod'sstack
frame?
![Page 531: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/531.jpg)
Furtherreading
Thefollowingbooksarerecommendedifyouwanttoknowmoreaboutgarbagecollection:
DesignPatterns, byErichGamma,RichardHelm,RalphJohnson,andJohnVlissidesIntroductiontoAlgorithms –ThirdEdition,byThomasH.Cormen,CharlesE.Leiserson,RonaldL.Rivest,andCliffordSteinDatastructuresandAlgorithms:AnEasyIntroduction,by RudolphRussell
![Page 532: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/532.jpg)
NextStepsInthisappendix,wesharethereader'slearningoutcomesfromthisbook.Thecoderepositorylinksandkeytakeawaysarepresented.Referencesareincludedforthelatestdatastructuresandalgorithms.Tipsandtechniquesareprovidedtohelpyoukeepyourselfuptodatewiththelatestondatastructuresandalgorithms.
![Page 533: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/533.jpg)
TechnicalrequirementsInstallGoversion1.10fromhttps://golang.org/doc/install,beingsuretochoosethecorrectversionforyouroperatingsystem.TheGitHubrepositoryforthecodeinthisappendixcanbefoundhere: https://github.com/PacktPublishing/Learn-Data-Structures-and-Algorithms-with-Golang/tree/master/Appendix.
![Page 534: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/534.jpg)
LearningoutcomesThelearningoutcomesfromthisbookareasfollows:
Improveawebormobile application'sperformanceusingthecorrectdatastructuresandalgorithms.Understandhowanalgorithmsolvesaproblemandhowthecorrectdatastructureischosenforaproblem.Enumeratethevarioussolutionstoaproblemandidentifyalgorithmsanddatastructuresafterdoingacost/benefit analysis.Getagraspofthevarioustechniquesforwritingpseudocodeforanalgorithm,allowingyouto acewhite-boardingsessionsandinterviewassignments.Discoverthepitfallsinselectingdatastructuresandalgorithmsbypredictinghowfastandefficientanalgorithmordatastructureis.
Inthefollowingsection,thekeytakeawaypoints,papers,andarticlestobereferredto,alongwithtipsandtechniques,arediscussed.
![Page 535: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/535.jpg)
KeytakeawaysThekeytakeawaysforthereaderareasfollows:
Howtochoosethecorrectalgorithmanddatastructuresforaproblem.Howtocomparethecomplexityanddatastructuresofdifferent algorithms forcodeperformanceandefficiency.Howtoapplybestpracticestoimproveandincreasetheperformanceofanapplication.Real-worldproblems,solutions,andbestpracticesassociatedwithwebandmobilesoftwaresolutionsareprovidedinthebookascodeexamples.
![Page 536: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/536.jpg)
NextstepsInthissection,papersandarticlesareprovidedasfurtherreadingforeachchapter.
![Page 537: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/537.jpg)
Chapter1–DataStructuresandAlgorithmsThefollowingarticlesarerelatedtodatastructuresandalgorithms:
ThecompleteguidetoGoDataStructures(https://flaviocopes.com/golang-data-structures/)DataStructureandAlgorithms(http://www.golangprograms.com/data-structure-and-algorithms.html)DatastructuresinGo:Stacksandqueues(https://ieftimov.com/golang-datastructures-stacks-queues)
Thefollowingpapersarerelatedtodatastructuresandalgorithms:THEREPRESENTATIONOFALGORITHMS – DTIC(https://apps.dtic.mil/dtic/tr/fulltext/u2/697026.pdf)ONTHECOMPUTATIONALCOMPLEXITYOFALGORITHMS(https://fi.ort.edu.uy/innovaportal/file/20124/1/60-hartmanis_stearns_complexity_of_algorithms.pdf)AnalysisandPerformanceofDivideandConquerMethodology(http://ijarcet.org/wp-content/uploads/IJARCET-VOL-6-ISSUE-8-1295-1298.pdf)
![Page 538: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/538.jpg)
Chapter2–GettingStartedwithGoforDataStructures and AlgorithmsThefollowingarticlesarerelatedtothecontentinthischapter:
Go–Datastructures (https://golanglibs.com/category/data-structures)Applied–GoAlgorithmsandDataStructures(https://appliedgo.net/domains/algorithms-and-data-structures/)EffectiveGo(https://golang.org/doc/effective_go.html)
![Page 539: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/539.jpg)
Chapter3–LinearDataStructuresThefollowingarticlesarerelatedtolineardatastructures:
DataStructuresforBeginners:Arrays,HashMaps,andLists(https://adrianmejia.com/blog/2018/04/28/data-structures-time-complexity-for-beginners-arrays-hashmaps-linked-lists-stacks-queues-tutorial/)Stack-ArrayImplementation(https://www.cs.bu.edu/teaching/c/stack/array/)
Thefollowingpapersarerelatedtolineardatastructures:Linear-SpaceDataStructuresforRangeModeQueryinArrays (https://cs.au.dk/~larsen/papers/linear_mode.pdf)RESEARCHPAPERONSTACKANDQUEUE(http://www.ijirt.org/master/publishedpaper/IJIRT101357_PAPER.pdf)LinearDataStructuresforFastRay-ShootingamidstConvexPolyhedra(http://www.cs.tau.ac.il/~haimk/papers/ray.pdf)
![Page 540: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/540.jpg)
Chapter4–Non-LinearDataStructuresThefollowingarticlesarerelatedtonon-lineardatastructures:
Overviewofnon-lineardatastructures(https://medium.com/@ankitkulhari/overview-of-non-linear-data-structures-40cb441f6d7)Non-linearDataStructures(http://euler.vcsu.edu:7000/9647/)WhatIsForestDataStructure?(https://magoosh.com/data-science/what-is-forest-data-structure/)TreeDataStructure(http://www.cs.cmu.edu/~clo/www/CMU/DataStructures/Lessons/lesson4_1.htm)
Thefollowingpapersarerelatedtonon-lineardatastructures:Y-Trees:Anextendingnon-lineardatastructureforbetterorganizationoflarge-sizeddata(https://ieeexplore.ieee.org/document/8234528)AShapeAnalysisforNon-linearDataStructures(https://link.springer.com/chapter/10.1007/978-3-642-15769-1_13)RepresentationofNonlinearDataSurfaces(https://www.semanticscholar.org/paper/Representation-of-Nonlinear-Data-Surfaces-Olsen-Fukunaga/f4f4812532ba427658ecc83d772637c076780acf)
![Page 541: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/541.jpg)
Chapter5–HomogeneousDataStructuresThefollowingarticlesarerelatedtohomogeneousdatastructures:
USINGMATRICESINGO(LANG)(http://connor-johnson.com/2014/06/21/using-matrices-in-golang/)Golang:Linearalgebraandmatrixcalculationexample(https://www.socketloop.com/tutorials/golang-linear-algebra-and-matrix-calculation-example)GonumTutorial:LinearAlgebrainGo(https://medium.com/wireless-registry-engineering/gonum-tutorial-linear-algebra-in-go-21ef136fc2d7)MatrixMultiplicationinGolang(3x3matrices)(https://repl.it/@hygull/Matrix-multiplication-in-Golang2-matrices-of-order-3x3)
![Page 542: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/542.jpg)
Chapter6–HeterogeneousDataStructuresThefollowingarticlesarerelatedto heterogeneousdatastructures:
HeterogeneousArrays(https://gist.github.com/cslarsen/5256744)OL(OrderedList)(https://www.w3.org/MarkUp/html3/seqlists.html)LargeOrderedLists(https://www.aerospike.com/docs/guide/llist.html)ImplementinganOrderedList(https://bradfieldcs.com/algos/lists/implementing-an-ordered-list/)
![Page 543: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/543.jpg)
Chapter7–Dynamic DataStructuresThefollowingarticlesarerelatedtodynamicdatastructures:
ThecompleteguidetoGoDataStructures(https://flaviocopes.com/golang-data-structures/)DATASTRUCTUREANDALGORITHMS(http://www.golangprograms.com/data-structure-and-algorithms.html)DatastructuresinGo:Stacksandqueues(https://ieftimov.com/golang-datastructures-stacks-queues)
Thefollowingpapersarerelatedtodynamicdatastructures:THEREPRESENTATIONOFALGORITHMS – DTIC(https://apps.dtic.mil/dtic/tr/fulltext/u2/697026.pdf)ONTHECOMPUTATIONALCOMPLEXITYOFALGORITHMS(https://fi.ort.edu.uy/innovaportal/file/20124/1/60-hartmanis_stearns_complexity_of_algorithms.pdf)AnalysisandPerformanceofDivideandConquerMethodology(http://ijarcet.org/wp-content/uploads/IJARCET-VOL-6-ISSUE-8-1295-1298.pdf)
![Page 544: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/544.jpg)
Chapter8– ClassicAlgorithmsThefollowingarticlesarerelatedtoclassicalgorithms:
SortingAlgorithmsPrimer(https://hackernoon.com/sorting-algorithms-primer-374b83f3ba09)Depth-FirstSearch(https://medium.com/@g789872001darren/gogoalgorithm-1-depth-first-search-582eeb58f23a)HashinginGo(GolangvsPython)(https://medium.com/@vworri/hashing-in-go-golang-vs-python-b7bc1194e967)IterativevsRecursivevsTail-RecursiveinGolang(https://medium.com/@felipedutratine/iterative-vs-recursive-vs-tail-recursive-in-golang-c196ca5fd489)
Thefollowingpapersarerelatedtoclassicalgorithms:AMathematicalModelingofPure,RecursiveAlgorithms(https://www.researchgate.net/publication/220810107_A_Mathematical_Modeling_of_Pure_Recursive_Algorithms)RecursivealgorithmsforestimationofhiddenMarkovmodelsandautoregressivemodelswithMarkovregime(https://ieeexplore.ieee.org/document/979322)Recursivealgorithmsforapproximatingprobabilitiesingraphicalmodels(https://papers.nips.cc/paper/1316-recursive-algorithms-for-approximating-probabilities-in-graphical-models.pdf)
![Page 545: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/545.jpg)
Chapter9–NetworkandSparseMatrixRepresentation
Thefollowingarticlesarerelatedtonetworkandsparsematrixrepresentation:
EquationsAreGraphs(http://gopherdata.io/post/deeplearning_in_go_part_1/)FromTheoryToPractice:RepresentingGraphs(https://medium.com/basecs/from-theory-to-practice-representing-graphs-cfd782c5be38)GoDataStructures:Graph(https://flaviocopes.com/golang-data-structure-graph/)
Thefollowingpapersarerelatedtonetworkandsparsematrixrepresentation:
RepresentationLearningonGraphs:MethodsandApplications(https://www-cs.stanford.edu/people/jure/pubs/graphrepresentation-ieee17.pdf)Anoverviewonnetworkdiagrams:Graph-basedrepresentation(https://www.researchgate.net/publication/308049492_An_overview_on_network_diagrams_Graph-based_representation)Designprinciplesfororigin-destinationflowmaps(https://pdfs.semanticscholar.org/587a/730b11a4b3878142bd4995f80dc969bc5982.pdf)
InChapter9,NetworkandSparseMatrixRepresentation,usecasesfromreal-lifeapplicationswerepresented. Learninghowthenetworkdatastructureandsparsematrices areappliedindifferentdomains,suchasairlines,banking,medical,pharma,telecoms,andsupplychains,isagoodnextstepforthereader.
![Page 546: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/546.jpg)
Chapter10–MemoryManagementThefollowingarticlesarerelatedtomemorymanagement:
GettingtoGo:TheJourneyofGo'sGarbageCollector(https://blog.golang.org/ismmkeynote)Moderngarbagecollection(https://blog.plan99.net/modern-garbage-collection-911ef4f8bd8e)GoLang:MemoryManagementandGarbageCollection(https://vikash1976.wordpress.com/2017/03/26/go-lang-memory-management-and-garbage-collection/)
Thefollowingpapersarerelatedtomemorymanagement:AnalysisoftheGoruntimescheduler(http://www.cs.columbia.edu/~aho/cs6998/reports/12-12-11_DeshpandeSponslerWeiss_GO.pdf)SimpleGenerationalGarbageCollectionandFastAllocation(http://www.cs.ucsb.edu/~ckrintz/racelab/gc/papers/appel88simplegen.pdf)ATime-andSpaceEfficientGarbageCompactionAlgorithm(http://www.cs.ucsb.edu/~ckrintz/racelab/gc/papers/morris-compaction.pdf)
ThedifferenttipsandtrickstobeusedinGodatastructuresandalgorithmarediscussedinthenextsection.
![Page 547: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/547.jpg)
TipsandtechniquesTokeepupdatedonGo,youcansubscribetotheseforumsandblogs:
Gopherize:https://gopherize.me/?fromhttp=trueGolangWeekly: https://golangweekly.com/issues/240 TheGopherConference:https://www.gophercon.com/ GoogleGroups: https://groups.google.com/forum/m/#!newtopic/golang-dev SlackGroups:https://techbeacon.com/46-slack-groups-developers StackOverflow:http://stackoverflow.com/questions/tagged/go DaveCheney'sResourcesforNewGoProgrammers: https://dave.cheney.net/resources-for-new-go-programmers
ThefollowingsectioncontainstipsforwritinggoodcodeinGo.
![Page 548: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/548.jpg)
UsingchannelwithatimeoutintervalThesoftwareprogramthatconnectstoresourcescanbesetwithtimeouts.Channelsareusedforimplementingtimeouts.Youcanconfigureachannelwithatimeoutintervalasfollows:
//mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain
//importingerrors,logandtimepackagesimport("errors""log""time")
//delayTimeOutmethodfuncdelayTimeOut(channelchaninterface{},timeOuttime.Duration)(interface{},error){log.Printf("delayTimeOutenter")deferlog.Printf("delayTimeOutexit")vardatainterface{}select{case<-time.After(timeOut):returnnil,errors.New("delayTimeOuttimeout")casedata=<-channel:returndata,nil}}
//mainmethodfuncmain(){channel:=make(chaninterface{})gofunc(){varerrerrorvardatainterface{}data,err=delayTimeOut(channel,time.Second)iferr!=nil{log.Printf("error%v",err)return}log.Printf("data%v",data)}()channel<-struct{}{}time.Sleep(time.Second*2)gofunc(){varerrerrorvardatainterface{}data,err=delayTimeOut(channel,time.Second)iferr!=nil{
![Page 549: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/549.jpg)
iferr!=nil{
log.Printf("error%v",err)return}log.Printf("data%v",data)}()time.Sleep(time.Second*2)}
Runthefollowingcommandtoexecutetheprecedingcodesnippet:gorunchan_timeout.go
Theoutputisasfollows:
![Page 550: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/550.jpg)
UsingcontextinsteadofchannelContextscanbeimplementedinfunctionsexecutedinGoroutines.Contextsareusedinsteadofchannelinthecodeforpassinginformationbetweenprocesses.Thefollowingcodesnippetshowstheusageofcontext:
//mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain
//importingerrors,context,logandtimepackages
import("errors""golang.org/x/net/context""log""time")
//mainmethodfuncmain(){
vardelaytime.Duration
delay=time.Millisecond
varcancelcontext.CancelFunc
varcontexcontext.Context
contex,cancel=context.WithTimeout(context.Background(),delay)
gofunc(context.Context){<-contex.Done()log.Printf("contexdone")}(contex)
_=cancel
time.Sleep(delay*2)
![Page 551: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/551.jpg)
log.Printf("contexend%v",contex.Err())
channel:=make(chanstruct{})
varerrerrorgofunc(chanstruct{}){select{case<-time.After(delay):err=errors.New("chdelay")case<-channel:}log.Printf("channeldone")}(channel)
time.Sleep(delay*2)
log.Printf("channelend%v",err)}
Runthefollowingcommand toexecutetheprecedingcodesnippet:goruncontext.go
Theoutputisasfollows:
![Page 552: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/552.jpg)
Panic,defer,andrecoverPanic,defer,andrecoverareusedtohandlecomplexerrors.Thelastreturnedvariableinafunctionisusedasanerror.Thefollowingcodesnippetisanexampleofthis:
//mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain
//importingfmtanderrorspackages
import("fmt""errors"
)
//FirstFuncmethodfuncFirstFunc(vinterface{})(interface{},error){varokbool
if!ok{returnnil,errors.New("falseerror")}returnv,nil}
//SecondFuncmethodfuncSecondFunc(){deferfunc(){varerrinterface{}iferr=recover();err!=nil{fmt.Println("recoveringerror",err)}}()varvinterface{}v=struct{}{}varerrerrorif_,err=FirstFunc(v);err!=nil{panic(err)}
fmt.Println("Theerrorneverhappen")}
![Page 553: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/553.jpg)
//mainmethodfuncmain(){SecondFunc()fmt.Println("Theexecutionended")}
Runthefollowingcommandtoexecutetheprecedingcodesnippet:gorunhandling_error.go
Theoutputisasfollows:
ThefollowinglinkcontainsomeusefultipsandtechniquesforwritingGocode: https://golang.org/doc/effective_go.html.
![Page 554: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/554.jpg)
LoggingwiththelinenumberWhilelogging,youcanlogwiththelinenumberandthemethodname.Thefollowingcodesnippetshowshowloggingcanbeexecutedwiththelinenumberandthemethodname:
//mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain
//importingpath,runtime,fmt,logandtimepackages
import("path""runtime""fmt""log""time")
//checkPointmethodfunccheckPoint()string{pc,file,line,_:=runtime.Caller(1)returnfmt.Sprintf("\033[31m%v%s%s%d\x1b[0m",time.Now(),runtime.FuncForPC(pc).Name(),path.Base(file),line)}
//method1funcmethod1(){fmt.Println(checkPoint())}
//mainmethodfuncmain(){
log.SetFlags(log.LstdFlags|log.Lshortfile)
log.Println("loggingthetimeandflags")
method1()
}
![Page 555: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/555.jpg)
Runthefollowingcommandtoexecutetheprecedingcodesnippet:gorunlog_linenumber.go
Theoutputisasfollows:
![Page 556: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/556.jpg)
GotoolusageTheGotoolcompilercanbeinvokedwiththefollowingcommand:
gobuild-gcflags="-S-N"
Thelistoptionscommandsyntaxisasfollows:gobuild-x
Totesttheraceconditions,youcanusethefollowingcommand:gotest-race
Runningatestmethodbynamecanbedoneusingthefollowingsyntax:gotest-run=method1
ToupdateyourversionofGo,youcanusethefollowingcommand:goget-u
Copyingcanbedonewiththefollowingcommand:goget-d
![Page 557: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/557.jpg)
Togetdepths,youcanusethefollowingcommand:goget-t
Togetalistofsoftware,youcanusethefollowingcommand:golist-f
![Page 558: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/558.jpg)
GoenvironmentvariablesTheGOROOTvariablecanbeconfiguredasanenvironmentvariablewiththiscommand:
exportGOROOT=/opt/go1.7.1
ThePATH variablecanbeconfiguredasanenvironmentvariablewiththiscommand:
exportPATH=$GOROOT/bin:$PATH
TheGOPATHvariablecanbeconfiguredasanenvironmentvariablewiththiscommand:
exportGOPATH=$HOME/go
TheGOPATHvariablecanbeconfiguredinthePATH variablewiththiscommand:
exportPATH=$GOPATH/bin:$PATH
![Page 559: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/559.jpg)
TesttableTestsaredrivenbyatesttable.Thefollowingcodesnippetshowshowatesttablecanbeused:
//mainpackagehasexamplesshown//inGoDataStructuresandalgorithmsbookpackagemain
//importingtestingpackages
import("testing")
funcTestAddition(test*testing.T){
cases:=[]struct{integer1,integer2,resultSumint}{{1,1,2},{1,-1,0},{1,0,1},{0,0,0},{3,2,1},}
for_,cas:=rangecases{varsumintvarexpectedintsum=cas.integer1+cas.integer2expected=cas.resultSumifsum!=expected{test.Errorf("%d+%d=%d,expected%d",cas.integer1,cas.integer2,sum,expected)}}
}
Runthefollowingcommandtoexecutetheprecedingcodesnippet:gotest-runTestAddition-v
![Page 560: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/560.jpg)
Theoutputisasfollows:
![Page 561: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/561.jpg)
ImportingpackagesYoucanimportpackageswiththefollowingstatements.Here,weshowthreedifferentsyntacticaloptions:
import"fmt"
importft"fmt"
import."fmt"
![Page 562: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/562.jpg)
OtherBooksYouMayEnjoyIfyouenjoyedthisbook,youmaybeinterestedintheseotherbooksbyPackt:
Hands-OnSoftwareArchitecturewithGolangJyotiswarupRaiturkarISBN:978-1-78862-259-2
UnderstandarchitecturalparadigmsanddeepdiveintoMicroservicesDesignparallelism/concurrencypatternsandlearnobject-orienteddesignpatternsinGoExploreAPI-drivensystemsarchitecturewithintroductiontoRESTandGraphQLstandardsBuildevent-drivenarchitecturesandmakeyourarchitecturesanti-fragileEngineerscalabilityandlearnhowtomigratetoGofromotherlanguagesGettogripswithdeploymentconsiderationswithCICDpipeline,clouddeployments,andsoonBuildanend-to-ende-commerce(travel)applicationbackendinGo
![Page 563: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/563.jpg)
Hands-OnDependencyInjectioninGoCoreyScottISBN:978-1-78913-276-2
UnderstandthebenefitsofDIExploreSOLIDdesignprinciplesandhowtheyrelatetoGoAnalyzevariousdependencyinjectionpatternsavailableinGoLeverageDItoproducehigh-quality,looselycoupledGocodeRefactorexistingGocodetoadoptDIDiscovertoolstoimproveyourcode’stestabilityandtestcoverageGenerateandinterpretGodependencygraphs
![Page 564: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/564.jpg)
Leaveareview-letotherreadersknowwhatyouthinkPleaseshareyourthoughtsonthisbookwithothersbyleavingareviewonthesitethatyouboughtitfrom.IfyoupurchasedthebookfromAmazon,pleaseleaveusanhonestreviewonthisbook'sAmazonpage.Thisisvitalsothatotherpotentialreaderscanseeanduseyourunbiasedopiniontomakepurchasingdecisions,wecanunderstandwhatourcustomersthinkaboutourproducts,andourauthorscanseeyourfeedbackonthetitlethattheyhaveworkedwithPackttocreate.Itwillonlytakeafewminutesofyourtime,butisvaluabletootherpotentialcustomers,ourauthors,andPackt.Thankyou!
![Page 565: Learn Data Structures and Algorithms with Golang Level up ... · discovered Clojure in early 2009, and liked the simplicity of the language. Besides Ruby and Clojure, he is interested](https://reader034.vdocument.in/reader034/viewer/2022050109/5f46c35d3bacaf6f455a8dc0/html5/thumbnails/565.jpg)