Butthisonealwaysstuckwithmebecauseit's a fantasticoutwiththemandit's perfectandit's complete, andwe'lllookatthedetailsofitlater.
And I thinkis a greatexampleofprogrammingandcomputerscienceatitsabsolutebest.
Justincaseyou'rewonderingtoday I amlivingproofthatprogrammersandcodeisactuallygooutside.
Sotherewego.
Now, beforewegetstuckintothecode, I'm justgonnaprovide a quickprimerfortheuninitiated, andthatiswhatis a stackbecausethisisfundamentally a stackbasedalgorithmand a stackcanalsobeknownas a lifeOh, whichstandsforlastinfirstout.
Somepeoplemayalsocallitthefile.
Oh, it's thesamething.
Andtheideais, I wantedtoimagine a boxlikethisonifweputsomedataintothisbox, itsitsatthebottom.
Wealwayspushitemsontothestackandwepopitemsfromthestackonthetopofthestackisalwaysthemostrecentitemthatwaspushedontoitnowbecausethisis a videoprimarilyaboutalgorithms, I'm notgonnagointotheimplementationofthestack.
Therearemanywaystodoit.
Sufficeittosaythatifyoursystemoryourcodeuses a stack, itwillbehavelikethis.
Nowthealgorithm I'm goingtotalkaboutfordeveloping a mazeisknownastherecursivebacktrackingononesureoftheoriginsofthisalgorithm, butithasbeenaroundfor a verylongtimeandhassomefantasticproperties.
Butwheneveryouwanttowritecodethatinvolves a morecomplexalgorithmthannormal, it's alwaysgoodtogetthepenandpaperoutfirst, makesureyouunderstandit.
So I'm goingtogothroughitbyhandhereonthisverysimplemate.
Andit's fourbyfour.
Andalongthetopherealongmy X axis, I'vegotfourcell 0123 and I'vegotmy y axisgoingdown.
Myplanistofillthisfourbyfourarraywiththemaze.
And I'm goingtostartbyarmingmystackwithsomedata, and I'm gonnaarmitwithstartingcoordinate, whichinthiscase, isgoingtobe 00 Sothat's zeroalongandzerodownonthemark, thatcellasbeingvisited.
Soanycellsthathave a blueblobinthemiddlearegoingtobevisitedon.
I'm goingtoget a tickhere, and I'llknowwhentostopmyalgorithmbecause I shouldhavevisitedallofthecellsattheendonout, thereforehalf 16 ticks.
Now I'm notgoingtomakeyousitthroughallofthis.
I willspeeduppartsofit.
Butit's a nicevisualexampleofhowthealgorithmisputtogether.
Sofromposition 00 here, I'vegot a choiceoffthisneighbor 10 orthisneighborzerowarm.
I rollthedice, create a randomnumber, and I select 01 So I setthatcelltobevisited, and I create a linkupdatemyvisitedcount, and I'vepushedthenewlocationontothetopoffmystack.
Sonow I repeat, I lookatmyimmediateneighborsandchooseoneofthemrandomlythat I'venotalreadyvisited.
Sointhiscase, I'm goingtofillinwherever I haven't got a linkbetweentwocells.
So I'm goingtodraw a linehereonhereonhere.
Once I filledinallthelines, I'veeffectivelyjustdevelopedthewallsfrommymaze, atwhichpointwenolongerneedthestackandwecangetridofallofthisconstructiondata, whichleavesuswith a reallynice, albeitrathersmall, mazelikestructure.
Nowlet's seehowwewoulddothisincode.
I'm goingtostartwith a blankinMaineprogram, as I alwaysdo, and I'm goingtopullintheoneloneCoderConsulgameengine, whichyoucanseeinthevideomarksinthelittletababove.
Butultimately, I needtoderive a classfrommycounselgameengine, whichjusthandlesalloftheconsolesstuffforme.
Ifyou'veseenmyothervideos, you'llknowthatallofmyprogramsinvolvedcreating a screenbufferandusingget a stinkystatetoemulatesomesortofgameengine.
I'vewrappedthatupinto a nice, tidypackagethat I'vecalledtheonelonecode, a consolegameengineandtheirtwofunctionsinthisonusercreate, whichiswherewedoallofourdefinitionsandcreatingofresourcesandonuserupdate, whichisbasically a perframefunction.
Ifyou're a limitto a Macuser, thealgorithmisstillgoingtobeplatformindependentNowformymazealgorithm.
I knowthatit's fundamentallyStackbased, so I'm goingtoincludethisstackfromtheStandardLibraryandinthegameclass.
I'm goingtocreatesomevariablesthatdefinethemaze.
Specifically, mymazehas a widthah, height, and I'm goingtocreateanarrayheredynamically, whichstores a valueforallthecells, and I'm goingtousethisvaluetotellmewhichneighborsthecellisconnectedto.
Andsotomakethis a littlebitmorereadable, I'm goingtocreateonenumerationhere, where I'm definingsomeconstants.
Soforanygivencell, I cantellwhetherit's connectedtoitsneighborsbecausetheintervaluethatrepresentsthatcellwillcontainthebitsetintheappropriatelocations.
Andif I visitedthecellaswell, I knowthatthealgorithmalsorequiresmetokeeptrackofhowmanycellshavealreadyvisited.
Andfinally, ofcourse, I'm goingtoneedthisstack, andthismightusesomething a bitnewtotheonelongcodeofvideos I'm using.
Thepairtype A pairallowsyoutostoretwothingsatthesametime.
I couldcreate a structureheremyselfthatstoresan X and A Y corners, but I'm goingtousethepairanyway.
Whynot?
It's 60.
Andso I have a stackthatstoresanobjectwhichtypepair, butthepairis a templateIDtostoretointroduce.
The 1st 1 willbethe X coordinateonthe 2nd 1 willbethe Y coordinates.
Now I'm readytospecifysomeparametersthatdefinemymaze, someonetosetthewidthofthemazeto 40 ontheheightsto 25.
So I'm goingtopushontothat, a newpairand I'm goingtousethemakepairfunction.
We'regoingtostartlike I didwhen I wasdrawingitbyhandinthetoplefthandcorner, whichmeans I alsohavetosetthatcelltobevisitedandconvenientlythetopleftcorneroff.
Andasdiscussedpreviously, MeiMei's consistsof a two D arrayoffcells.
So I'm goingtoitstraightthrougheachofthecellsmakeswithinmatesheightandforeachcellinthearray, I'm goingtocheck.
Doestheinterviewhalfthecellvisited?
Bitset?
Inwhichcase, ifitdoes, wedraw a whitepixelor a whiteblockcharactertothatlocationonthecouncilorwithyourblueone.
Let's justhave a quicklookwhatthatlookslike.
Well, it's a bluerectanglewith a tinylittlewhitedots.
That's good.
I mean, thatindicatesthatourmazeoffthedimensions 40 by 25 doeshave 40 bluecharactersby 25 bluecharacters, andtheonecellwe'vealreadysettovisitedinthetoplefthasbeenset.
However, everythinglooks a bitsmallandthere's a problem.
Wedon't haveanywheretodrawthewalls.
I'm goingtointroducethenotionof a pathwit, whichwillspecifyhowmanyonscreenconsulcharactercelsrepresent a singlecellinmymaze.
So, forexample, ifthewidthissettoactuallyoccupy a twobytwoblockoffcellsontheconsole, whichrepresentsonecellinmymaze, then I cansurroundthetwosidestotheeastandthesouthoffthatonecellwithblocksthatrepresentwall.
Here's mytwobytwocellHereis a twobytwocell, andhereis a twobytwocell, andwe'venowgotpositiontoatwalls.
I onlyneedtoconcernmyselfwithwallsattheeastandsouthsideoffthecells, becauseiftwocellsarelinked, thenthiscelllosesitswesternwall.
I'm goingtolookattheelementthat's atthetopofthestackusingthetopfunction, and I'm goingtocheckbecausethesnackcontainspairs.
I'm goingtocheckthesecondelementofthatpair, which, ifyouremember, isour Y coordinate, and I'm goingtoensurethatisgreaterthanzero.
Nowwe'retryingtodevelop a listofalltheneighborsthathaven't beenvisited, soweneedtocheckthatinourMeseret.
Andtodothis, weneedtogettheindexNow.
We'recurrentlyusingthestack, andit's using a pairofsecondandfirstforWine X, andsothatlookssomethinglikethis, whichyoucanseeisbuilt a bitof a mouthfulwhenwewanttoseehow's thecellvisitedFlagbitbeenset, whichwilldobycheckingifit's equaltoone, butthisisn't veryusefultous.
A tallinfact, verydifficulttoread.
Andi y coordinateinthiscase, wouldgetreplacedwithminusonebecausewe'recheckingfortheneighboraboveothersinour Y axisonder, the X coordinategetssettozerobecausewe'recheckinginjustinvertically.
We'renotbotheredabouttheeasttowest.
Sointheeventofusbeingin a validlocationinthearrayonDDEthatourneighbortothenorthofusexistsandhasn't beenvisited, wewanttostorethis, and I'm goingtodothisbycreating a vectorwiththevector I'm goingtopushtoitsandidentify.
I canusesimilarcodetocheckformyeasternneighbor, whichinthiscase I'm goingtouseoneastheidentify.
Buthere, I don't wanttocheckforminusone.
I wanttocheckforzerointhe Y axisondhe, plusoneintheareyouknowwhat?
Thisisactuallygettingtoomuch.
I'vejustgottentothepointwhere I couldbarelyunderstandmyowncoat.
So I'm goingtocreate a littlelambdafunctiontohelpmeout.
LambdaFunctionsgoingtotakean X and A Y coordinateanddothishorriblelittlebitofoffsettingforme.
Let's changethattoanexandchangethatto a whyandsemicolongetridofthis.
Now I'lljustcallmyLambdafunction, so I'm checkinginthenortherndirection.
I know I'm notbotheredabout X, but I'm lookingatminusoneintheWhyThat's much, muchTidier.
And I canalsodothesameformyeasternfunction, whichinthiscase I'm lookingalongthe X axisbyone.
But I'm notlookinginthe Y axisitall.
Nowyoumightbethinking, Whydon't I justdothiswith a macro?
Well, ofcourse, youcoulddothiswith a macro, butthelanguagenowprovidestheautofeaturequitelikethis.
I likethelandoffunctionapproachtodoingthis.
Itmeansareforcedtoputthecodewhereit's needed.
Macron's couldbeanyworthonthelittlebit.
Unregulated.
Theycanget a bitdangerousanddeadlywillalsoexploitthefactthattheifstatementischeckedinordersowecangetridofthissecondarycalltoif, whichmakesthatlineofcodemuchmoreconcise.
Now I'm goingtorepeatthatfortheotherdirectionsonhere.
I'm stillunsureyetaboutusingsomethingliketheonelonecode, a gamesconsoleengineinthebackground.
I don't knowifitdoesactuallyacceleratethedevelopmentofthecodeofthevideo, but I'vegotsomeotherideasforitforotherprojectswhichrequirethingstobe a bitmoregraphical.
And I'm tryingtoavoidneedingtodevelop a Windowsapplicationanyway, Asusual, thecode's gonnabeavailableonGetHopeyoucandownloadit.
Hackitgeneratesamazesforme.
Ifyou'veenjoyedthis, giveus a thumbsup.
Itdoesgreatwondersformyselfesteemondhe.
Pleasethinkaboutsubscribing.
Lotsofpeoplehavebeensubscribingrecently, and I'm reallygratefulforsomeofthefantasticcommentsthatpeoplehavebeenleaving.
Sopleasekeep a lotof I'llseeyounexttime.
Hello.
Subtitles and vocabulary
Click the word to look it upClick the word to find further inforamtion about it