1) Algorithm Notes Made
1) Algorithm Notes Made
Blam) Genie ccheu on Length of paltun/
0. of element (0 the patiun
Compallt ts Coubsheig) wales co O(n-on41) tims
| Compass elt exes shifts Been) + Bcm-oner) ~ Gln) lems by
Compowing p with ab to (G= 0... meomer
by using Hous Ru ual of Pa compared:
How Ruel Euccluats ole of & polynoanil
Pe planJs to PLon-1] + to( Plm-2]4-- 4 to(Ploq+ toPcq)-- ))
| Enanple Geauen Po; 32731
| > Bxtolt 2x (024 TRIO 3xt0 +1
i No of cmutlyplrceclow 2 4434+! = © mullylicatw
| Ato of onllipleratooms cen be hecluccel by
i pulling % = (0
| © 3444 9484 7224 BXdE
: 1 (3U212KEF TRASH
| > a (1 (32249447)43) #1
| : a(n (9 (3x42) 44941
—_— tI
4 No: of omaltplicateons = g — 9m)cm) € ;
Stnilaaty we con fond a sehshiing wrth los a ts a asincow of
StK am:
tsvr = tolts— 0" r[ser] + TE saan]
Fg. m=. 623456246
ts: YS6 29 tse = Se2a¢
fsars (o(asera- sy) tS
| = WC US629- lly
| = w(Se2a)es
| = S6204+5
|
= 662¢5
So omly shifting u meccled which can be cicheud em Conalint bmi
+ Omly problema when am G large of mot porseble bo Stoxx im mounal emt.
Mettching ol o Constant Luwe
Sou emsidr modulo curithmelte - emplayes reccmance selakion tov
| ber = Colts ~ TEs# i] - 10 Mmmedq)) + T[srome]) aod 9
| A348 407231415 2673 49 2. Qelz
| Cie 2 1 fees
mod 3 faodl i Pr Biya
| 2y 27
phen 2 module waluu aut epual pufoum comparcny
when 2 modulo wtlus au clifeunt tb thew tho Me pallan
| count Match
14162 = [tolsrqis- 40° "3 mod 12)+ A) nod 2
| ? [to (C31uts- 30000 mod 13) +2] mod Iz
\ = to[arqis - g]42] med 4
2 (0-3r4Ob42
= 3/4062 mod 13
=¢dh ts pmodq) Hen tS 4p bo shye Sa rmualid
but dts sphnodgy dew met Oleoays meaw tsp
Check alm chenoclu
Any shyt ¢ fo whioh ks = plmedg) must be teslect further
So the tut ts = plmod g) helps & mule cut tmaatid shy S
Rapin taup- Matcha (7, P, dg)
m: T length
he a™” med g
peo
bo=0
for F< Om ff Peaproerssing
p= (dp + PLé])mod 9
fos to + TLe])modg
for $ <0 &a-m Panatcheng
f pez be
te PLI..-m] == TEset ... S41]
b Peultun ooowus txt Shift 6
8B. Sea-an
tu. ter = (da (ts- Tsti hk )+ 7 Ese mei]) mod 9.
22 wu aH & SP >
| When © u orecudtd t& hit - 1 checks fot gpurwas hit
Prsproeuncing lie = cam)
Matcha bina = O(m-m4i)™)
Shing lian = bw
Enpeclid Motch = O(nem)+ Tieme for spurtous het
- OyKNUTH - HORRIS: PRATT ALGH
* Computing Prue Atnay
Patten: ac acabacacabac ac ac
Take a Cemmpouuy any tofuch ct Of same ege of pattur
Eauny pocat on Gomporary coucay tril BU ws which uw the longest buff
Length cohiok alo has-the somu o prafiw at Luuy powit
|
| sfats| | s]aloleiniaiw| elala
| olelalblolelalelalgjolelale iol
| |ilalalolrla)s 4\s 6 Fe) 4 1 H)
uu
io |
omen TET] PT LT
Semoument jor | | |
Compaut v(Q:uy) - | tt 1
t | yo ave ! |
D pul joerg 7 |
fee ie I |
VCO. Yer j : 7
ow (Hy Ji : ‘
VO? VO) WO Hg i e rc |
Jel J Put o> Xl6) |
Ved? UG)> yor fj oT
fete jae | |
J oT | i |
| i C |
cb| Tomp 3) longest Suffer which abo Mal cher pufim ws
Ch ftom Chae auxt $ charoes amertch S prin
| hast posulton welt be 3ero, f after deseanenting oo Onaleh prumel-
KMD. Subslumg Suuth
tHrus gre
tut abebog le ->m
Palta- begl —>m
| Woast oom OCamm) bone (akin
KAP pufoum subshhing soxch on Olmsn) teams:
toon
Text» abcxabedabx abccdabcdabey
pelt : abe dab oy
| Text abxabeoabe a by
| 1 23 | & 6
pall: abe a by
| eq fololo]r| 2 fo] Proper ous
| abraheabeaby
| ahe aby
Puta ec
So agai ¢ out farm oy patin nd a?
abrabeabe aby.
hoo
of tet
boolzo!
7 t
ahr abc ah caby
t ao need urruiong fo 136
| abeaby
| ti hw Just mau 2 backwords
|
So start Cmpauinng row ¢ aby unth Coby| Rantione Conplertly OC) ams langth of text
Runtime bb bucld onaaey » On
So Lote Cnme > OComt n)
Space lompleacty > OCm)
compu. Paap Facleoat CP)
am. P. Length
het [t]he 4 rer Ono
npiy=0
ko
for a= 2 ba
while k>o and Plk+] ¢ PLQ7
ts Xk]
of PLen d= Pl gl]
Does ker
*fa]-k
Rolo ©
| Compats anatohes P agaenst tb ef”
Running Tiame analysa
| Ran ning deme of prtfion fo « Blm)
@ | white 6-7 execu OCam) trans albogetu - Mabe an-1 duolwn
hen 4 slab) Keo. and K tnorronenttig at Lin 9
tors exreuted! ortth for trop - atonost tres per enceritiom of for loop-&-00
|
|
>
> FRM MY nN Dow >
Tolol cama tn £ = Ms
eq on enlinig fos loop» €ach elnalton af loop thovoment 9
So arpignements wr Cro 3 ond rq enscas KEQI<¢ fora Qzl.. ™
| a chats Loop duoeases k
0 Kaew becomes -
Jotét cesseast of K fom while mp & bourclia ftom obow by Cotes
Cnoreose Of & ov Linp 2 am-?-
@KHp_Makcher CTP)
BF
Form UNH dS woe
+ ame T-Length
. m+ P. Longth
Ke Compal Pacfen.Fuunclem CP)
qi0 -n0of characla matcheo
era ~> scan tut pom byt & cughe
whi gro and Plate] # Th]
Q= Rg] .-> nert choroclir dloesmvé amatch
Sp Plas] = = 10t]
Qzqt! .-> mert Characlts matches
qe ls ay Pmatotud 2
‘paltun occurs totth shyt
aq X0q] bee bm rat amalth®)
a
| COMPLEKITY Classes -
\-
cto P: Yes/No problems auth a polynomual ham culgan
Polynomecd fim onecuns
|
|
| Ih you ou gruman anay of a Cnleger i /Oa,.- An
wean asked & scorch an elerment ty that. shir can he acheined ty
| tunncng & fon bevp (€ om
| Searching among m nos: OC)
| 4 OMG polyneenial tme
| Yes/Alo problems anecins efseciacn problems
| lays up: beewsuom prcblamy - Ya/Ko problems with & polynomial lie
| “checkeng algonither amore precy tly gras 0 tolutton (kg: Subset of wel
| Wecan cheok in polynoanial tems Y that soluliin G what eve om lockwy
| fox Cts tk o Clique of size ta
| clagusr- Hears att mock tnluconnsclisl & tach oltes °
nave Ba chow
Peotuded age we Can check Y tho clique 0 Noe
S prowrcled a solectim ese corn aucuefy polynoonial terme
| aBep - a aol o clique © polynameat fn .
is PENP?
% 02,03... An —
Soattng O(mlogn) GY polynoaniad terms
0)’, 0p’, a3’... Qn’ be Scalia oP
Can we cuaefy 2 a eorlid anray or mot ?
Foa thet check Y AZ A2¢ ag -- Z£Qn1 EQ
PENP‘ue Penp hut P#NP
Fg: Show that CNE-SAT & % NP?
p- Find a s0lulion w polynomuat fms
Ne- Check 0 soleelem ur polynomial Cnn Vrotsol boi
How b procws a problom & Wp Complete 2 = Bekma
NP Had- A peoblum Np. hoxol tf all Other problims on NP com be
momually keduced & ie
ret
wp kes: A problem G NP comple f of & om NP and NP Had
‘The most: abifcouclt problums on NP
fh cur tolue cm NP har! om polyncenial tunie then P= NP
Alp.
| Complue proputy
oO All pans that axe on Ne that bas he seduced & a Np. complule pom im
| polyrecual Ls € NP
An tur phomalh com be xudleieed (0 NIP Complete pbm wi polymoonead Gui —>
fon solued Qruwur com be setaced os the onsite of NP-
j Po
| NP— Hane
| due femal a bolultn for amy NP complete problim - aneans awe have fy
| Golutuon fox NP clam of problems
| Neel of Atp complet - Froudrng a polynomial trom
joneth
{tempi plan ps Sead emech oigouthon fox aay NP
How b proous :
Grusn a prblom &-
pu NP phers can be tecluced bo NP compli ' Quy NP Complele
pl coun he Soluued tr polynowu'cl tix Chen Ol! UP plms can be
solusd vr polynoowuienl “Cus Thy P= MP6
pore selutiom exes fox NP Comp Cole pom - dhow NP plu Cannel be sclud
ry polynoanial iu
| Proow cx problem & MP complete :
| Reoluctiom Method
To promt tx pb B as NP complete - (b hoxal
| Tea that take a NP complete pom which & abeady known be be Ke-cenplel
Rephiose Alog
Rephaouing emapluyca oH polynomial tune -
| Fnslanee —y——. Inslancr —s[Potynomal | % :
| Geof A Potynemutt poof we nye Fi eee —s pele
Tame Recln ta Be | © he
| Bleck Bow
' Tastaner wef A & homfoumed, So mow which becomes am Yp fos ph B
| Reoluuclrem wi polyrnomicd this ax polynunuial toms algmy (clan P)
1) ea
| To Show bu Kte Compl.
Osté wu ti Ne
© Toke a pb t¢ known & he AP cemplelt , ancl Recluce Ue te phm BO»
polynomial tome
Cneerall phn Of Solwurg A cuing B hos 2 parts Cfo clecuion phm)
olhuwae 3 pare
Easy (0) + Easy (0) - Eay
Eosy@ 4 Yad a2 Yao
Bord acts leks botttr oeck
Jp B com be solued om poly normal Cue cé (P) «Then ts P ushich Contact
| ch orsunpliow of Aa AIP Corup loli + Bence prooutd
| You gprs phos - Comet to cectien Pls.
| w Quaph coloteng ph - Amd the cmiincanun no of Celocus
Dieu im - Con & graph Colowud tengo ColouCss P: Poms that aur goluatte tr polymer tere
Pbims that can he solucd tn O(n*) deme for soone unstant &
and Ns Size of put b phim.
LloasNP + Phams-that au werifcatte ch polynomial bans
Peuyfeale: gireen O cerifecate of @ soleeteery, toe cam eieelfy ewhethes he
eurelefetals Us corecl in polyneaneiel “tem
Fg: aurupyirg O gruen clique
3. cme Goutts feability
Any phan PO AID Ih Pabmu 0° P, then aue cam solwe th en polynconiod
time without enen beng seppluiol ty a con tepeents
POND
Ne Coomplele: day phm o Eu NP ancl NP harol
any AP complete phm oon be Soluabl or polynonrad Gare then euirg
Atp phan hos a polynoonrtsd mts olgm
Commonly useed tp Complele phm w cuscutt cates frcrbelety.
we Foe thal qualiees Of Yp, the ceoeull well qeue Op 1
Pacers Cleque ph w Kee Comply
Show Cheque a NP 6
3-CNF can he seduced te Cque
Beer u 4 Clique
grun a clique wimg adjacency amatux of each wouter
een proowe conneckeclnen of aertix So NP.
3-cnrF phm U olwacly brown as NP Complele
SNF Recluclem! ko
Opa Polynomral om
aly, 2
GAGA C3 - Cn
3cnr ‘
coteuat sat ” gach cloww conten Ovevb.Ch VOvla(h via) A
Neca fe Lransoum this fe eulance k-ehequ
Potynomcad Sane sigon dns. ~ Cor ap of Buse, tre aetenal Case Hans Ranainng
teane algouithan & Ofm*) for some constant h. Atl problems cannot be So(we
tA polytoméal brme: Taring Haultig Problem: connct be sotued by any
Compeitur Thou aux problems which cannot & folurdl tr Ota!) tums
Sroblems that ae scluable by polynomucel bony algan cated ay Traclotl:
Pacblerms that eget baporpolynoomc terme Us nbactable (had.
No polynoamut fume aulgmm hax Atscound fe ain NP Comphele problem
“class P- consisb of problems that am soluabts tn polynernectel tems
Paw blems thett coun he solued tr teams O(n) fox scone Constant &,
= Size of Yp problem. . : i -
Class ue conesh of problerns that qu turifiatls orpolynonmct tis
i Grauen a eerig cate’, tolucligar“eue Lan woufy the eestfeeate W Conseel
0 tims polynomial @\eseef tp of preblom |
Ege Ginn a patb, can cheek 4 the path & Harméltoawan eyo robin
SCN galisfcebclaty , coutyitale wtowld be wrignement of eelees b
sariable - We can check o> polyncemtod line that assiymanent
Sats et boolean foumula
any pachlem wn’ P & also NP. as any pblim Pu solucbte 4 chacously
aunufrable ewclhout een sepplued ty a cntificale So PE NP
Ne comple- kU 05 NP and & as hawt as any problim w NP
Hany np complete problem Lan be soled i polynoanceu Lemie, excerss
btoblum tn NP has polynocmical tune alge + Host secatst beleewe NP
Complete problems as mbactable~Thu awe 3 hey concepts vi showing ¢ a -pacllere. fo be NP Comptila
Dreucoo peetlomn vs Cplomizatton problem
Epleangatcon problem wy whch each foasible olution has cn ance ales
ucilue and cut weeh b frord @ foastble sclutom wth heat Ueleee. +
Deeeecon prchlems au those i» which nsiin ch ALamply ya or m0
Relatcom blo eplumegation phan and a telolid aleeu con problem works
w fawoce then wwe want to shew te ophmtselom 4 hod thea if
Wwe con prouccle emvictencr that olecduin phm & hard, we abo cap piowa
eurdliner that rolalel eptionizatcon problem & hava
|) Redtercleoous
The motto of Shoutng one problem
| anothn apple when oth._proble Ou gees wet problems. Thy clea a
stake b prooue {AIP Comp irs. bots t clu a dacuton problin A,
ea Shpul & particelas phrn u
Called as enstance of that Poms epee be knoe how & Soteu o cifewn
daexécon phe B th polynoomtiel Gore Fry we! hous a procecttue hat
brounsfoums any wislaner 0 ef A enlo gum eit pot @ wtth the
‘
fottouning chauactuistees : \ \
oO no barca thar
ss Aescat ue the samt, we onset of 6 ans of PU Yes
Sucka nocedu called as Polynomial he °
r “d fet kin OE”
Tbe
iste wal gaa — | Chaos Potyearnaal toms
isa _ Sy ee 5 Nara | a
___ Potynormucad Terns agro & cecal 4 |
Reducing™ 3K
£4" Poltoud. RhoC!4) f : :
. we 8 By)
fer 4
Nek » 3
yr2 t
lee ue
dohule Thue /
ir2, (2 | rey _
ay = 1 ano 14 32 Get med 14 Fy 2 byrl tod ITD
d= geo(a-3, iq) =f | dr Gen(3-@,18) =F br Geo(3- 0,1
| peo ay
yolesk Qere | ih ceek Bz-y |
yo?
rou tyfoo. Ut
Kiergt 2 -
fos). Xi > toy med)
Mea Fx) mod we
DK? et
eo (Fd ky ~ v2 |) me)Hopute:V !
| Pobabulslic Atgouthon
~ Some culgonctham behaue cefferent avhen ub u opplud teuries for te some
tastanet. “26 execuleon Amu and eLuen ofp may vary emmsictorably
* 6 allouud © go t cnfienele loop dition by joo ot peouudded of cocwus
| with reasonably small puchability on any youn trstance, | alge geo
Stuck, scomply testart on same uislance fon a push chance of scour
4 ip thus y amoee than ov Corel ances, seuual olffacnt nay be oblaunsd
| by cunning probabilistic algorithan anu than once
=| Algom whow the wueell and way of xesult eblacned olepend! an chance
| Also costed 0s Randomised Algorithm — dlepencls on tandorm aes for tbs
Oprrateoas
| Computer comn genaati on Preudowandom not. @ Nos that axe genualed by
| apie bat meennbu Cooks candom.
| _ Honte Caste dlgm - Hoy prodlivcs ineorseot wrull with
probable? — bounded ea pe shabhly
Randoanized Algms \
has Vegas Algre — produess comecl cescitt ane
only uration from one @ anothu un ke the hunny
tem
© Hoolyfeid determina tic alg wstutch uses eancamnoy
om decision
+ When dead ond xetal the algoutton| Monte Caro ALGORITHMS.
| Imconporate puobabulely into ana
7 sed evhen ave brow that a set of scenarios can happom but av rintus of
tohether they will happen
| oman world as a syslomn
+ Founelate avoild os battle 6
+ Each sep ot dexation pi 4 tual Sf world
1 'yslom tll euentually eontucrge to adoirab meas we
t HC Qoed for: Examine complen Aggregateans fon stomps o.eleows
\ nconporating ceneerlatnly onto analyses
| Kaploueng anintecbon tect
| Semplfecateom of comptor systame
+ Sconseemaly anaes onestober
+ Peobabulity w Eypcal fos Monte Carlo alms that gobi clectscon phim
+ Momte Couto Colors con be geen an euplecit Upperbound on loleat. enon
| Pecbability
| Appleone,
(0 Gptemizatiom stun
5 panty coma foma probably de bebuteon
Y
[Dm ancetocleotiones Engg. tb analipe conclatid ond uiluconclaltd uaation
| 0 dnalog and degelal integrated cbt
12) qeoslodi Lees ~ arnenerel piveasiong , flow Shere quantitate Ae cnatyse.
9) computational bology- Stuctyong brologccal ystems
(A Jating puonalty of mor
(DP Decteleng Set Equ
6) Applicateoms Cryptography
(9) uuyying Habicx Mellplecalon
r A keinclomized alge ath delumeaus ke running Gam , but ofp may be
fneovset wth 0 culain piobabilityVeufying Mater Meultyphrcalton
Consider 38 nxn omalrias A,8,c ket C= AB
Meultiply Aand & and compare woul wrth ¢
Ip eauong shiaigh(fourmd mali amultplicaleom algonthon tho: tabs pun lms
Of Olm) + Stranens Algm 6 fos and eusn {asl lor onus fo aery douge n
tut the asymptotically faslisl algm cwnentty known alll kequuu a meen
Ofm?34)- f wie au eotleng lo foluale ct smett probability ef oe ”
Cent om OCn2) 1s suypectent to Sole This preflear a Cohen tue
peobabiliste clgm O(n) a Suuppectent
ASsumu C #AB
rr ¢ fu onal: ¢ now of d contains allecal one non joo deg
Console. cony subset Se $1, 2,... 03 / —
kat 2,0) = vetlot of tengih ba obtained ty adding porit-wtse the KoWs of
D indluxed ty ofeanents of &
For tastance Ft 3.43 (2) 6 oblarined by addhing fost 3nd o tows of b
Testirig whetha ov mol CAB by computing =5C0) for o tandemly chosen
| Seb S and Comparing xslt cuth 0. Thu can be dom ofectiauly by
wrtthout fast Coomputing b :
| Consider > a 0 emabuin melleplecolton of «6 oun
| ers ahmary actor of kngth a 2 AI if Jes cand %-0 othaurse
| . . _ We
j We enn unify sharghtty =5(0)= x0 @ a ran nalux
| So cox tut & about checking whelhu x(ne-c 4 0
Ol AB = XC for wancloanly Chosen
bunacy cuectos *.
Habu fare of OCn2) compute XAB - Os helio t Compalt
4 bn matlitx X ann. Inatux.
Funcltom Fiurualds (ABC,
fon (<— Hom
do %<— Undom(o... 1) -
Ih (#A)B = xO then xeleun True
else Reliun FASCFalse 05 Qnsauer amecuns AB AC, eegaudlus how onary Bimeus ous getlely
i Ams TRUE
9 Comselo a 3x3 mate
|
az [) 2 3 p-/24 4 c- |" 24 37
| jas 6 ts 4 my os
| 764 265 a 4S
|
|
| = ya
| x= [1t,0)- benny eectox
Ly Aca om Funiuatdt (8,613) outs x2 [2]
|
xas [1 op ft 9 3 (44 ers 346]
4s 6|-
yea) B14)
| cae: (B74) [3 ) ; 2 fisnite — saas4sy — dorearys]
| s 4
| ; ‘| [40 aq re]
xe + C1 off 24 27)» [i129 vanes 37441]
29 6s
47 a 98 2 fo 9 128]
> cal frornalls uth x= [or
xae for gfe 3) = [ar see 644)
GS 6
y é » (vu a J
2
(nse (O18 05) 1g) + (eaptze lt eset 4g enF795)
1s 4 2 (t loy 336)
| es
efor J(u 2 34 )> (1 thy 136)
| ag UL page os (x Ae
43 4 4%
Go aut hous b Aapeort Facinalds b tinwesFunction Repeat Feevuatas (n.B, ¢, 1, &)
fote-1@k do
Nh Fremalds( A,B,C, m) = FALSE then Reliun FALSE
Retun TRUE,
Sh au the K tem, olpo tue then C* 9B
I) C#AB, Jon cach cat on Frervalds that d wit action tun with a probably
o to. Cincoaect)
Probability that & successctue colts each eeloun relunn vovong ansiuts 4
atanest gt
| So ween concluice com alg & 2" couset
| When keto, he & belle thon 99-9% coneck-
‘Pecherbility 6 typical for Monte carlo Aly that solve olecctem paohl. de th
ansuu Y obtained & guacantied & & consct
| Mont canto atgms can be gineen an oxplrect eipperbound on lolviats evo
prcbobelty
Feunctuom Freeeuldleepstlom (Au B Cy, E)
kK—[y Ye]
Rel Rope Paucualals (Cn)
An odateenttige of-this aerseen of aalgon a that ue can ancelyse tht runncng
fans a3 0 functivm scaneltancously of urslance 8130 dined exor probebildy
Thorlake Wins O(log Ye)Mint. Ct (WA NETWORK:
Hem-cut means oruoucmum that fh
| hae req sheowna pein & ediges Should be cut from raph, 8
Randomized Hin-ceot Alora perfoums only wher then enut atleast 2
uerliers ancl ore eddge. Rerrdlennizeattom & perfoomuceel for Selucling eclge
Tind_Mincut ( uaclieetid Geaph 9
' while thee at mo: of modes > 2
do
2 Pio an edge G,w al random” Gg
(3 Combact the elge
(4 Rumoue al Loops
Ss Oulpul the temareeng edges
Fa |} —-—-—-8 MoncutG_
— bohuele Ivi>2 :
| { Sotoctand vdge Cry) €
Q—> (—— tnsfounty at ca.don
| contact Cy)
| Retuun Let
| 5
| Comacela the edlges Ge), (48), Go)
Combat the oage an Remow al i
6)
| (cn) & > ne
|
®) Pee
| ff
| Ld)
(th d= ncen cut ead peettetitcle
| Then G has alleast ho ealges chor m+ mo, of noclu wh gaphSimes graph has ancncuk of attest dl, it must haus amincimevm dcegeer d,
and thu alcast dn edges
2
Puchability of pickrng an edge belonging & cut en just Slop ote
2[LIS vegas ALgoeinucy
|= nenctomnegee algan that alucays gran Cousot ascot ov (L trfouns abt
the frelon
+ Ege @eurck Sout - Pintot chosen raxctona, but toselt aloowys sorted
t t always ema Ofecluely, but tk aay ofp 4 symbol not past of
_ Golulisn space tr wideeab facts
T Nodytid cletuomenestic atom by wing tondomnex oh clectt cen
1 When dleac. end restart the algm
+ Mewiage reennving me anetlysct eumumes sores dlirbrbatton ef problem
inslaneu
£g: Qucek Sot , Sefeetom Sot
| £g= Cemscclu: problum of feodteng a’ en an amay 0f 2 elements ,
| Taput: An cw.ay of nd temnens » which hal au a's ancl othe hal
bs
| Cutpett « Find an ‘a’ in ase
| Fienetenga. tv ( aay A, 1)
Begn
Repeat
Randomly select me element: fron nn Chumentt
| Unt a @ focend
| Fool
Ngo succeeds with prohabelety 1.»
| Quek gout
+ Afamcliar algm wheu Keundeannen 4 dmployed
= Detrumemeter @turck soul ECQULULs O(n2) & soit NNO
| ~ falgmn selecl prrot element at xaotdom, Olnlog n) Hane Keqiued
+ daplace
-| ty eequus O(ntegnd
Wows O(n?)
+ Diawde amay into 6 and Solus eecouusiruly
5 coud ns ee pict therment canclonly
Mea ee
2 @ 1 9 4
nar weluchd 8 atl wwalle “Cument @ lt of pro!
faxga elerments & taught of praeot
|
| Pracol Seloolid xandoon
[ omen tach elermens Uh pruol ander i ond
= Exch, both @
UG Cument ebemmunt < Pieol Exchange cunntnt Cerment
Certs
ob
2 eo1% 4 ?
? Tyre
| a Vv
2row ¢ & @ 4 7
| 4 .
i tinea ome ofan Cussent > plot
| e@ 6 9H > i -
| a + tot Simply Susop
me index <> prwtSelsclzom Sort:
| of
1 tm vat er
| Ye yo
| Tet 1 small Camus S
| s2y 9 4
GCF yw ,
462 mo omievel:2, — CrCheg 1 pote with 2
, 8 @€ 8 4 97PROBA BIISTIC. ALCOR ITHNS.
Randomness useal in alguns fo apptoarmate Soliton of mumuicad problems 4
Close oxarmple for aucimnerical prohabileche atgmn sconulalicn. Eslamal amsan
Length ef @ queue w 0 sqstam so complar that uw enfeasublr to gee Closed fous
Sotcattoms ox mumoical anseuer by citucminit lic amethed Anccuws abld by
Probabilistic alan a approwmaticn, but ik expects precitton Compo actin.
jauatlab to algm encuaws. eur ¢ _
Jannl 6f wso%k performed
8 lo obly tre odecteomal digit of prctiten, (00 limes auoUk ex ecelic
Sotegua
Pree? wa conttinuons function and q a <6, than aa of the sonforr bourcs
by the comme y= fo, Tho t-ami and the wotreal tones %=Q anol ¥=6 &
6
a fforde
a
—}__ t 1
a b
Comsida a wotangle 6} wxdth b-a and height 1/6-a. as Shown. hea of
uctongle and sunjpet beloco cuuau also of game Aiea Ano! Sams wtdth , Chey anuat
haus Somes aunrage heught- We conclude rat cueing heightey curus bho als
@ 2 (b-a)- f we labs a pernt beloeo., (0 take cugatow hughe, ther caluprete.
also Aotolt fou anbultuy continous fastion f:R—>R
A peobabilishis algrn jor her &- To esteonal amg haght of conus by xanclom samplay
and anectliply result by b-a.| Saretion HcimeC 5m, 6)
| sam <—O
| fou (<1oan do
1 <— unugpum (rb)
| Stum <— seems fOr)
| totun (b-0) x (Seum/n)
|
|
Analyse Shous-Chat uatance of estate caleutatid by alga 3 ciaeusly
| preeportiwmal fo mo. ef sample prints. Dahchalim of estrmale & approximalely
| moumat aohen mcs lauge & alimal: of ence ot
| d
Viebia
| A tcasom bo «we HonteCeslomnteqatiom & when tut haus te ewateeale a omatlepe entegeot
(dpa deturminusle align & sannpls the flr gencialized fe seucral dtoncnsiar , the no
| Sample points nected f& gel deter precuien gous exponent rally -oxch chimenven
of miagral b& be tualuated f tco ps merce b euatuale a sianplr nleg tall,
then ‘© aie (0000 pb ef a oor 100 gud f> acheeut Jame puciiter when double
tntigeal eccaletalid » Ome mutton ps cstlt be neccted foe a buple calegtod . fn NCaly,,
demension of enlagqral hos little effect on prcesscem cbtd, eucn though ant of
work fpr each Uralion increas slughtty wrth dimension
Numi « ced fe entalate enlignal 4 demseston fou 4 heghe
% mo chee Somply Uchniquee can Compete Beller algmms cub bul with anon
Complication Precerton of pbms Can be Compe ceed sung hy buecl Lichnrigues pautly
Systemmatia and pully probabtlestie
Counting
doth an m dit regal, toxin oxcinay. ot Ser can count upto ati fom o
‘The ugulu oan count mo anon than &” duilincl Ualues a UU the anak No,
ways fo set or brneny Ualues we can count beyond 2” & ws Skip (ntuos dar
tales . kg” 1} wwe count only exin nos ttt Con Count Upo lies cbabatl
Waluus Kee c= mn bit tageslu Baretumes Cali lenote the integer topeesental
bray fy the rages
(Sino proctdias ws complemented tratCo
; ckCD
@ Juncker Count Cc)| counter) = Retwins. the m0. of Calls b toh) Sion Last call en cnet
cnt Cc) - Resets he cocinlr & 3e00
lekCQ - edolt one @ county
count) - aste fo h consent walue
digms Should be able & onainlarn arbitany lange mo.of eruntest C1 C2 ---
No infgnn con be paused blur Calls: exciple dough tugulr w@ expliout pacameler. Wf
detaninistic counleng stsaligy eoventing connok stip walues. Thaw & mo atu way
tcck con add ¢ fp corenty for any oltoe call» Bohowior of UckEawn anust be
| dlotaeamencel by cumsant af cuatue of ct thu @ value 0 9 URACO temas
unchanged counts willick ab that pe until mut co) Called « A detuominuslic counting
‘nou than a” ouonls to an obit agit © tmporslbt- Fle cut hows € lax the rubs
teluun the be: of Ficks Sines last init
i A profabilétie stintgy €© count tuubt fas &- Regula ano
bunawy count, chutiated do 300 on ang cit. ete iad sated pace,
{f headl- ado Ib kagcalte + f taut lo nothing cohen count tt dalled releun tunes the
| terlue alsned gate
© peowealune tnitco
c<0
PHocadune beokcc)
foo cic do
ih coun = head thon xefean
cecer I Pkobobility of overflow «3 too Small to be woith checking
Function counrtCc)
Reto 9S
| Counteig turce fox oneons aplo aln., which can be achuued actually bY O Single
| addubmal bi 0 Kegciters Probabuldle counting Saabigy com count exponantrelly
| fata 0 © OLY « 8 hub au sufistint & Count onow than Sx107euumnb.
| Fos tut exp register an ostumale of legauithon of actual no of ticks.
count telmn aoe Senor count ef 0 & be ssprasenled Wwe Slat thy slab wacky ¢
| Cus ediaral of to.of tok: breomu 1-1 ceuth probabelity whl
| wwmains 9&1 axt complimentary probabilety | P
| apeold alee Keluined by count Co) ofl tha lich 0
| (ath npsetntep = 242-1
||
|
|
| By matéimaticol induclion we can proous that uaxtonce of count afm ticks
fa anln-n/2 - Slardad ceutation w toughly toh of actial ne of cuunts
| kasegas Algoruthans
Hobs probabalitia choien fo hulp quucl thurm mone quuchly oo easiest
They news tulun a uneng Answer. 2 main covleg Ou ef las wages colg ms onal
1 ce tandocmnes fo quit thet stauch § 0 cobuet solution 4 Guusonterd elisn
| anfostunate chovees ae ameicle © Allow themvelues te lake usreng Guns that
| bung thom te dead ond, u statu ih mpoucils to ford 0 solulion wn this tung
cli
hasaregas algm of ype used when a enon deburminsstie alga by colus a phen
| tens much foste om than tn worse cose fAUIcksoul - Inconporaiting a
element of Rardommer auow Walgm & umn AY} ble gerd and bod
untaness
| Funclum seleclwoty (1[1..n],s)
[ $ Feds the ¢gancillsl elimant rT Ie Sone
| fet jen
| Repeat
i £ Arse bus» T01..j7?
PetL unifour CO)
i pructbi CTE 4, pk,
Sek then jek
elie f $2 | Mente b
ele Retin p
Procootaus Quucksorthy (TL...)
{sorb subouny TL. .j) entornen deeuaseng xd?
Y jee a supfreunlty Smay then tnsal (1@i--{D
else
Pe-T Cisrsfoum Cpl
Pewetbes C TC, prh)
quachsont Lv OTe. £))
Atuchsont kv (70657).G nploxcty Clee of Loundomuzed | Alo
RP class Class of cecisiem problems for which the a an ofccuent polynomial
Gms Kanclomiged olga tohich Aecogaczer NO trslance with absolult
| Certainly and yes urlance with probability of atleast Yo.
| Zee. Problom classes harumg algans wrth polynomeay farms Cuerags Lore
[running fume whase Op u aloays corel Chas vegas)
| BPP. Class of problems fos whroh both Ves and Ato (rslancu ay allowtel
> be edentyfced weth somu euon ° Represents the cham of effcount
| candomaca allgns
ZPPC RP & BPP
| PP. Descutbes cleciscon problenms asth a polynoameal tamu digouthm eur
& mou acourale thon probabuldy Y2 but enor prcberbulity cannot
be bounded auoay prom
Random ed Polynoancal Clay Reclass) - & the complexely class of problem
for whech thon ens 3 propertte
9 SE always tun polynomial brane gp size
2D 4] Comet ansewu & No, ut always teGuns No.
3) Hf comet ans & Yes , Ut seluuot yes wath proforbululy allecst IpDION'S FACTORIZATION
& a genvial peepose integer [ccleugetlcom ancthod , bastel bn finding tong usuet
J sgaus modelo unlega
Congreuenes Gf Sqacus :
dng contegar om canbe eeprecentid a n= vy? = (04 pap
224? = omodn & n[a?-y?
Garyperg) = omodn
DE sorme Hone nr nevtha denucles Gey) o% Cx-Y) alone
£9: n=3s
36 mod as =I
86 = ¢amod 35 Facto =< Geo(m-y, 35 , Geo(X4Y, 3S)
Qcep (6-1 135), Go(6rtl 35)
Us
_ Dekoats, Theosemn,
het on be a Compost entegus « ket and b be a oltsteick inlegus blo 120-1
Such that a+b zn
f a2anod m = bancdn then gco(arh,n) wa aon- biwel dbraison of
Comidu N= 2534
Aut A= 2012 and b= 29 ath An
2012 40127 VEY F QS37
aancd n = 2012°amod 2637
9: 1sas Re (69g
Banod” = acl $22 Soon +1629
q= Soo R= (b29
i a? = (545m +629
Q2. bs mod
ti a®ancdm = b?anodn ital 7
Hon a#b and ath zo. Theosem says Geo (a+b n) = Qco( 3/39, 28394
43 & anon Keoual Arter of n& Select any emligu rk
9 Choose an lege % tandomly from Items
3 Compute Y= aanod
4 Foctuze Y
Sf facteu ef Y au pace and oot an elment of &
16 ghen choo anothu tnlegn %
else Cooutwuck ker x & matux Mu which erty Mij u Zuo
th J prcane appeass be be an ener pocuar tn Me faces ef Ye
7
S — Othauue Ae 2
Fg? massa .k=F Comsictuthe 7 paces
2,3,5,1, 0, 13,17
Fast tonlegus blo 1 and 2536 Say = 1769
Cleutak ds squcur medulo m: a%= 123304 Ryo 116? nod 2537
9: 1233 &= 1ay0
y = yo
Faclouge y uw tayo + 24xSx31 He
| Farle snes 37 a oot decwiahe by any of he adomaside ZR Pe
Pacomes and abo 31 & mot in 78mooth os 2 A
2 31
| Second attermpt- > 2y55.
|
dul on?
Galeulob. Sete amodulom. mod om 2yss2mod 2539
» a G> 2375 2 l6So
2,
Focloune y > loso- axaxs Kt 650
| “am
| Record, comtorenig (hes lentil @ buccuE 2 Tes:
' = QYSS + 16S axaxs xu “y \,
= 970 Ya = 200 DKS KIBKUF ae
%= 0S yg = 728 Q2PKIXIS a ;
| My INS yy = 2296 Bex 5x17
As 2 2b Ys: MO 2x32vsxU
| te: 8 Ye. 32g © DXB KIBKH
| Ag = (UY yas you 22x 99 ¥F
%w = 433 Y= Dogg 2YKI Ietr
He 2 3 5 F NB oF ka
‘toto o0 ' @ © chkow corsexpomds b one sucrty
| he o@ 1 9 o ' 3 Each column costspunel t O18 of
| Lo © 4 0b © | Aclamessebte preianes
rfo t 1 0 @ :
sft ot © 1 oe
t]t wo e@ott
| r}Jo totore
| sLo oo ol 10
Tirtows bhould be Selecled and amu
| utiplicd based on folloun conditoms °
| D Eaponents th the procuck ort euon ue ¥ wd
2) Thos aust exul a nom ermply sel- of tems that adds up ard fr!
the ktmaindn using qodulo-2 and Kull Choeld be 300.
W¥rYyyg = ake atestx nex 132x177
Ys Yy Ys Ye ¥a > 08 x a! x etx 12x NRX IS? % 7%
| @, Expomenb th thee au eusn- Tun find the squeue joot Of produc
6 folreted Hocus , then wrth aod a and tu tuomed as a
‘as [RRB TRE TRUTH IBEX 172 mod 2537
= Dana Ax SP? KUK BR 17 Mod 2537
b calculated as b= Ny K Hy XM HE ood 2537
= 2YSS RK VIOX GSE XY 33 nod 2537
The condliteoms a2 anodln » b2 aned and Qtb#% w& gatifed
@ and bam tnleges bua land m1
Gul when que Cos Yr 3 Yo Ys Yo Ya
s
a= o8x3@Ks*x 72x IK IEXIF Mod 2527 = 1972
be QUES X NOS Xiyse y2/b¥ COX (EGYY Mod 2537. ~ Sey
The quolaby te condition arb snMopuse
SOUAE VI Peltemene cwhethie any pes | lone segrmenty ntact
WEEP TECHNIRUE fot of Sweep hime Stata
US PEVENT Por
Reine seucip lechnque & cn algonttham fer deltmemong echethe any treo line
| Begonenls ma set of segancnls unlescet thes aulgontihem ccs technique
| Calica as suueepen
| Atgonttham Kerns tn O(n a tame who m= no. Segements Cue ake Gruen St
Acteeonvaes coly whethor ox not any trluscelsain euuts, Uk dowsanct print at
| tnluseeteons [Inoout cox b fd att entusrbi asl of mtensegments cont nb
| dat Seucrping an Conaginary wcrtioal surcep leat posses through goaun set of
| gevanuhive. ebyjcols feoan tft lenght. Ihe spatial dmeenseein cofuch Ue suceiplin
pmrcaues crorons,, of terben as diemension Of tume, hoe % dimension
| Yao anumphors ou made : GY No tnpult segment w& aeorbueal
O/No 8 input segements enltasict ata singh pont > Didkusng Sigmment
[100 assume cro extioal segment, Any gp segrnint enlawecting te scverp Cras wt
be cot ore pothe. So we can oudu the seganente nlusecterg bu auserp line Guuth
spect & ther y- woudhate of punt of iteueelesn
| Tuo soymans $1 and $2 axe sad lo be compauable at, 4 the eerbial susep
Gena with 1 coorclnate % cntuseets both of thum. KS; @ abouts. atx, We
wpnite as SXyS2 » Hans Sand % axe comparable at %, Inluscelion of
sweep lent % with 9 O hughes thee eatuseclton of So
_b
(®
Aaduseg of lene segamends:
Obs.c; ASLb, HSLC, ArtC cin SUC Segment A 4 Mol Compacahy
toith any other segonenb
h Seganents cand f , they Aree otdus aye. infusecling Edy. but fAwear scwceep Lie an the shaded aagecn hos sganente Ceand f) tonseculiue n
Ceclourng grown by ex
Tor ang grown %, the ruler dau ketal precoder for the segancn ts
tritervsecting te seuciplenen:. The dclaleem 6 tonite (81> 9S 2 SedHS
and nefloninse Segonent on(ta oudawong when us left end ponl
encocnlond by swueep and it Wouees oraleieng when tight enofpornt
w entountud
Mowing the seumep leone
Suuerp laine algcrthan manage 2 set Of datas
D Suucip frou ‘Slatia and 2) Equent porit Schedule
1) Stucep ine statis grows the Kelateorshyp among the ebpeols that the
pe vit "? ad “
8) Euunt pout schedul uo sequence ef point calticl event pons, which
ue ovoles from Uf tb mught aceoucling fo % coucdchats « ls the sucep
Peogers from eft bo right, ochen Ure Bouerplime tucicher o cooudinat
an ewent point . the stueyp halls, process the euuent pocnt,, ancl
‘then kéicimes: Change > avteep Lt stectus Cees cl cunt pools
Thu algorithm detucrumes ecueat pourts befor % depu on Som
pecpeuss of aputdata » Kach ‘the at ccipant & an et po
we orl the 9 and poinls by trowasing acvedrautte ano proceed
form Lyfe te eaght. When 2 0% ances endpocnls aur counlicas and
Df thay haw sarms a-cooudtinalr, tee 6 breken by pulling al kyl end
pounls befou corselécal wght enc pout |
3) Wen on a seb of corwelical Aft end pours » those with low y-condenae
aur pact (ust
when a seqanenk left end pone encountued , ux miert Begarunt into
ccueep Line Status. thon aught end point encountud, we delete segeut
from burcep Lime storus. uchen Hux Segments become consecutive ‘ti
(otas preocau, check whethu they inteucet
Seep Lane Status & a otal precedes, wseeheek eehethen they wrtaoeet
and Acquis follouring operateoas :INSCRT(T,8) ° tnsert Gcgaacnt § into T
DELETECT,S) * Delele segment ¢ fremT 7
Apove (1,5): Reteun the seqanent ammedralily above segment sot
BeLowlTs) + Reluun the Seqaent emanedralely beloce sega t 8
ff enput contac segment , ecech epaation @ performed tn OCG ny sing
Red ion Tee
Segment dnleaseclion Prerclocude
Tnput: Sot S of m Lene seqanontt
pau of sequins an Sintuseols else FALSE
| Oudlput Reltans TRUE yf om. me mu
‘ prea
Rel Black fee macnlans
drug. Segment Inbaseel(s)
® Fakatgedo ¢
© Sone the ond pounls of segment th S fom left boreght,
break Lit by putting Left endl point Befour aught and pork,
Bacak forth ted by pectleng pourk wrth éocu y coowltnate. i
® [oe each pont pe Souled Lut ef endl pownb
® h pe yt md pout ef @ Segmnt $
© INceRr (1S)
® U QBourC7 s) extib and wnlincots ¢) oe
(arlow(,9 exib dna tnloucct Dkelun TRUE
If pad faghe endl pocnt of a ts
Y both Above (7s) and Be cow CTs) eoust and
AboveCns) niu cok Betow Ces OReuin TRUE
ee
Dw pecene (15)
@ Reruen ERGE
Analyses
1. Srotralize Toted Puced be ennply
9. Doluomeene the cunt pourit Schedule by souteng om eeqanent points
cha & done by soxting arelpucnts on (M4 er 9) + uy > Coouctonatis
2-0 fou bxpt end point» e-1 Jor tughit ond pointEach cualicn ch fen (cop 3-1 proces One cunt pont:
[h pus lyl endl poure of segment ¢, leat S adds 8 to produ.
Kens 6-7 Releuns TRUE if S eenltuscole exther of seqomunt -
Boundary condition ovcu if p lus omanothiu segment ¢'- bx plrer
Sand 9 into 7. pw aight ond pont ofS, me aelebe poem poorly
Lin 9-10 Relwn Tue | thew w an entus ection ble seganents
soraounding 8 ch tolel puocely - If reganents donot mntusect barn
Cletus seganent ¢ form preouclo «Featlly y awe cree fren any
inteuseettoa af proosssing cal! Qn euun pound - le gelusns FALSE
FQ: Eaeeulcocn
a
a
c
b
wese
eon
eoee
> Tio
Foch qualicol kine & 6 lore at any euent pout
kecespt for tughtanost susewp tae , Orekuceng ef Seganent below each saxs
(ire = Total PuroudelT at end af for loop ctxses pordling euunl pont
Rughtomeal 6ceesp (ort ooceess peocentay the tighond pocnt of
Segment cw Segarents dand b somourd ¢ and (nluscols each
otha.
Ramet Teme n(D=S Asrimn t Ofnign)lwe
| 0-0
- og me (aap so “Jotat 2n ps - Qn hte
‘60 for lecp atonotl one paw euent pe
| tach dual. ©llge>F Lach cng ot).
go Deed OC Gr)Cousotons of day Segment dntescel (51)
We welt pre A61(s) cel Actusn tru Y anel only f Mere ts an coleseclirn anniny
Seganonts @ S~ Cxomiso ~ AS) wut relur bute if Vine is O Wnlcectira
Weactd leghoos-thar conucrse loo - Sf the & an enterseclion Ast Will Cute
~ Soppou thou a atleast | calercolion
~ ket po the Uyftomest enlou column pt, cheoen by Keabeng Lu . pt wilh focus!
Y conolinale
a,b be the seganents enlirsecting at p
* Senet cro entuseoleens secu to Lift of p, ovolur qeusn by 70 ena.sel fps pit lo off p
~ Skner no 3 Lines inlusrcles at cams pl, a and & become conscouln tn (las
puoide al dome seep lene
~ & 3a lo oft of p 1 gow Chiough p
~ Soma q be 0 Seqrnunt end pont on p 2
'b pa on Pusey Lent 5 hn 9-p , | pumol on sueplics g tron g u Left of p
Fulha case of 14 cousek befor enconnla g,
Kethe, eucal g us peocencol As; on & mot prneved
-$4 puownal, by 481 only 2 posschle acltars may Oca
O thn a bib u cunled mo T, elha segment YU Abow o below bo
letar presi (4-2)
© Segment aond 6 abeady ww 1. and Segnm beturin Uherm celetea,
and nabs Q aud 6 oumscoulus (0-11)
Echo cox tnlasden p delecla! amd Wt Kelun tus
44 auent pe 4 Mob proowmcel by AST, procedune may hase relunccl befa,
perewsing alt cunt pont ho wo & aeacly found an (niiuclen -S
| LINE SEGNENT INTERSECTION PROBLEM
| Do the graun dime -seqrens intusect
| EQ gf te dines GPa), Bepy do entustel a not ch
| if they cu paxalel, they dont “eset ;- A .
Guan of gcrms Lines ane nit parcial then aro event inlscel
fo
"
if cue noes the deecetiom of & wort Gre) and ve
Py wit (B,Pr) %
| a the ang Bu making 4 te aneanieng of ctsackton
> ceuntectorine GRE Fh Ci) ergbeng Counlucloobunne (2) avd
i othu an clockante - Then hanes lo inlissect-
On oppose Scola.
Chack for clucctuon asl Pe jor @s,Py)
Cheek for duration of QP) wxl fo Ps ancl Py
fh att ceeuning clockwse and antectockurue
’
; Thun both indir ects
) courbelerty Aan
Sb
ne BAD 0 m)- opposite side.
Be Mlockwue
fn
r
eloebanise
elec wie toe Py (Bo, Py)
Dy . Sou side
a % lunes wont enlisect
t
| Fox lanes to be wnbewccteng (P,f2) Should be epposrls cluecttoms wore B.A)
© and .u) should be spposite dueclons woeth respect bo (hPa)
DB ameght be mths rw (sR) ~ tot emtaseot
\ h
—h
My; Pe
.
RCH P,P) “Tr gens th Countuclockaue o% Clock unte
Retwur CP: - pe )x (B-PO)
on_seg CF, Pj, Pe)
Crier Couey 2) 2 oy & Mae Ce» 5)
AND ( HIN YE 143) & Yee S nan (Yer Yj
Return TRUE.
ese
Retin FALSE
Seqament dn tnsect (Ay Pe, Ps Pay)
ch = diel Ps, Py, Pi)
2 = DIR Ps, PysPe)
dg = pir ( Pr Po. Pa)
dy = PIRC Pit Po, Pu)
4 G20 92 d2