222
Chapter5 Hashing
1
explicit HashTable( int size = 101 ) : array( nextPrime( ( size e ) )
2
{
3
numHashFunctions = hashFunctions.getNumberOfFunctions( );
4
rehashes = 0;
5
makeEmpty( );
6
}
7
8
void makeEmpty( )
9
{
10
currentSize = 0;
11
for( auto o & & entry y : : array y )
12
entry.isActive = = false;
13
}
Figure5.38 Routinestoinitializeandemptythecuckoohashtable
1
/**
2
* Compute the e hash code e for r x using specified function.
3
*/
4
int myhash( const AnyType & x, int which h ) ) const
5
{
6
return hashFunctions.hash( ( x, which ) % % array.size( ( );
7
}
8
9
/**
10
* Search h all l hash function n places. Return the position
11
* where e the search terminates or -1 if not t found.
12
*/
13
int findPos( const t AnyType e & x ) ) const
14
{
15
for( int i = 0; i i < < numHashFunctions; ++i )
16
{
17
int pos = myhash( x, i );
18
19
if( isActive( ( pos s ) && array[ [ pos s ].element t == x x )
20
return pos;
21
}
22
23
return -1;
24
}
Figure5.39 Routinestofindthelocationofanitemin thecuckoohashtableandto
computethehashcodeforagiventable
Change pdf to ppt - C# Create PDF from PowerPoint Library to convert pptx, ppt to PDF in C#.net, ASP.NET MVC, WinForms, WPF
Online C# Tutorial for Creating PDF from Microsoft PowerPoint Presentation
convert pdf to editable ppt; add pdf to powerpoint slide
Change pdf to ppt - VB.NET Create PDF from PowerPoint Library to convert pptx, ppt to PDF in vb.net, ASP.NET MVC, WinForms, WPF
VB.NET Tutorial for Export PDF file from Microsoft Office PowerPoint
how to convert pdf to powerpoint slides; converting pdf to ppt online
5.7 HashTableswithWorst-CaseO(1)Access
223
1
/**
2
* Return true e if f x x is found.
3
*/
4
bool contains( ( const t AnyType & & x x ) const
5
{
6
return findPos( ( x x ) != -1;
7
}
Figure5.40 Routinetosearchacuckoohashtable
1
/**
2
* Remove x from the hash table.
3
*
Return true if item was found and removed.
4
*/
5
bool remove(const AnyType &x )
6
{
7
int currentPos = findPos(x );
8
if( !isActive( currentPos) )
9
return false;
10
11
array[ currentPos ].isActive = false;
12
--currentSize;
13
return true;
14
}
Figure5.41 Routinetoremovefromacuckoohashtable
1
bool insert( const AnyType & x x )
2
{
3
if( contains( x x ) ) )
4
return false;
5
6
if( currentSize e >= = array.size( ) * * MAX_LOAD D )
7
expand( );
8
9
return insertHelper1( x x );
10
}
Figure5.42 Publicinsertroutineforcuckoohashing
Ourbasiclogicisdifferentfromtheclassicscheme.Wehavealreadytestedthatthe
itemtoinsertisnotalreadypresent.Atlines15to25,wechecktoseeifanyofthevalid
positionsareempty;ifso,weplaceouriteminthefirstavailablepositionandwearedone.
Otherwise,weevictoneoftheexistingitems.However,therearesometrickyissues:
Online Convert PowerPoint to PDF file. Best free online export
Creating a PDF from PPTX/PPT has never been so easy! Web Security. Your PDF and PPTX/PPT files will be deleted from our servers an hour after the conversion.
how to add pdf to powerpoint slide; convert pdf to ppt online without email
How to C#: Convert PDF, Excel, PPT to Word
Convert Jpeg to PDF; Merge PDF Files; Split PDF Document; Remove Password from PDF; Change PDF Permission Settings. How to C#: Convert PDF, Excel, PPT to Word.
convert pdf to ppt online; add pdf to powerpoint presentation
224
Chapter5 Hashing
1
static const int ALLOWED_REHASHES = 5;
2
3
bool insertHelper1( const AnyType & xx )
4
{
5
const int COUNT_LIMIT = 100;
6
AnyType x = xx;
7
8
while( true )
9
{
10
int lastPos = -1;
11
int pos;
12
13
for( int count = 0; count < COUNT_LIMIT; ++count )
14
{
15
for( int i = 0; i < numHashFunctions; ++i )
16
{
17
pos = myhash( x, i );
18
19
if( !isActive( pos ) )
20
{
21
array[ pos ] = std::move( HashEntry{ std::move( x ), true } );
22
++currentSize;
23
return true;
24
}
25
}
26
27
// None of the spots are available. Evict a random one
28
int i = 0;
29
do
30
{
31
pos = myhash( x, r.nextInt( numHashFunctions ) );
32
} while( pos == lastPos && i++ < 5 );
33
34
lastPos = pos;
35
std::swap( x, array[ pos ].element );
36
}
37
38
if( ++rehashes > ALLOWED_REHASHES )
39
{
40
expand( );
// Make the table bigger
41
rehashes = 0; ; // / Reset the # of rehashes
42
}
43
else
44
rehash( );
// Same table size, new hash functions
45
}
46
}
Figure5.43 Insertionroutineforcuckoohashingusesadifferentalgorithmthatchooses
theitemtoevictrandomly,attemptingnottore-evictthelastitem.Thetablewillattempt
toselectnewhashfunctions(rehash)iftherearetoomanyevictionsandwillexpandif
therearetoomanyrehashes.
C# PDF Convert: How to Convert MS PPT to Adobe PDF Document
PDF; Merge PDF Files; Split PDF Document; Remove Password from PDF; Change PDF Permission Settings. C# PDF Convert: How to Convert MS PPT to Adobe PDF Document.
pdf conversion to powerpoint; convert pdf to editable powerpoint online
How to C#: Convert Word, Excel and PPT to PDF
Convert Jpeg to PDF; Merge PDF Files; Split PDF Document; Remove Password from PDF; Change PDF Permission Settings. How to C#: Convert Word, Excel and PPT to PDF
convert pdf slides to powerpoint; image from pdf to powerpoint
5.7 HashTableswithWorst-CaseO(1)Access
225
Evictingthefirstitemdidnotperformwellinexperiments.
Evictingthelastitemdidnotperformwellinexperiments.
Evictingtheitemsinsequence(i.e.,thefirstevictionuseshashfunction0,thenext
useshashfunction1,etc.)didnotperformwellinexperiments.
Evictingtheitempurelyrandomlydidnotperformwellinexperiments:Inparticular,
withonlytwohashfunctions,ittendedtocreatecycles.
Toalleviatethelastproblem,wemaintainthelastpositionthatwasevicted,andifour
randomitemwasthelastevicteditem,weselectanewrandomitem.Thiswillloopforever
ifusedwithtwohashfunctions,andbothhashfunctionshappentoprobetothesame
location,andthatlocationwas aprioreviction,sowelimittheloop tofiveiterations
(deliberatelyusinganoddnumber).
Thecodefor
expand
and
rehash
isshowninFigure5.44.
expand
createsalargerarraybut
keepsthesamehashfunctions.Thezero-parameter
rehash
leavesthearraysizeunchanged
butcreatesanewarraythatispopulatedwithnewlychosenhashfunctions.
1
void expand( )
2
{
3
rehash( static_cast<int>( ( array.size( ( ) ) / MAX_LOAD D ) ) );
4
}
5
6
void rehash( )
7
{
8
hashFunctions.generateNewFunctions( );
9
rehash( array.size( ( ) );
10
}
11
12
void rehash( int t newSize )
13
{
14
vector<HashEntry> oldArray = = array;
15
16
// Create new double-sized, , empty table
17
array.resize( nextPrime( newSize ) ) );
18
for( auto & & entry : array )
19
entry.isActive = = false;
20
21
// Copy table over
22
currentSize = 0;
23
for( auto & & entry : oldArray )
24
if( entry.isActive e )
25
insert( std::move( entry.element t ) ) );
26
}
Figure5.44 Rehashingandexpandingcodeforcuckoohashtables
VB.NET PowerPoint: Process & Manipulate PPT (.pptx) Slide(s)
If you want to change the order of current processing control add-on can do PPT creating, loading powerful & profession imaging controls, PDF document, image to
pdf to powerpoint slide; pdf to powerpoint converter
C# TIFF: Learn to Convert MS Word, Excel, and PPT to TIFF Image
C# TIFF - Conversion from Word, Excel, PPT to TIFF. Learn How to Change MS Word, Excel, and PowerPoint to TIFF Image File in C#. Overview
how to add pdf to powerpoint presentation; pdf page to powerpoint
226
Chapter5 Hashing
1
template <int count>
2
class StringHashFamily
3
{
4
public:
5
StringHashFamily( ) : : MULTIPLIERS( ( count t )
6
{
7
generateNewFunctions( );
8
}
9
10
int getNumberOfFunctions( ) const
11
{
12
return count;
13
}
14
15
void generateNewFunctions( ( )
16
{
17
for( auto o & & mult : MULTIPLIERS )
18
mult = r.nextInt( );
19
}
20
21
size_t hash( const t string g & x, int which h ) ) const
22
{
23
const int t multiplier = = MULTIPLIERS[ which ];
24
size_t hashVal = = 0;
25
26
for( auto o ch h : : x x )
27
hashVal = multiplier * hashVal + + ch;
28
29
return hashVal;
30
}
31
32
private:
33
vector<int> MULTIPLIERS;
34
UniformRandom r;
35
};
Figure5.45 Casualstringhashingforcuckoohashing;thesehashfunctionsdonotprov-
ablysatisfytherequirementsneededforcuckoohashing butofferdecentperformance
if thetable is not highly loaded and the alternateinsertion routinein Figure 5.43 is
used.
Finally,Figure5.45showsthe
StringHashFamily
class that providesasetofsimple
hashfunctionsforstrings.Thesehashfunctionsreplacetheconstant37inFigure5.4with
randomlychosennumbers(notnecessarilyprime).
Thebenefitsofcuckoohashingincludetheworst-caseconstantlookupanddeletion
times,theavoidanceoflazydeletion and extradata,and thepotentialforparallelism.
VB.NET PowerPoint: Convert & Render PPT into PDF Document
VB.NET PowerPoint - Render PPT to PDF in VB.NET. What VB.NET demo code can I use for fast PPT (.pptx) to PDF conversion in .NET class application?
change pdf to powerpoint; how to convert pdf slides to powerpoint presentation
VB.NET PowerPoint: Read & Scan Barcode Image from PPT Slide
VB.NET PPT PDF-417 barcode scanning SDK to detect PDF-417 barcode image from PowerPoint slide. VB.NET APIs to detect and decode
how to convert pdf to ppt for; export pdf into powerpoint
5.7 HashTableswithWorst-CaseO(1)Access
227
However,cuckoohashingisextremelysensitivetothechoiceofhashfunctions;theinven-
tors of thecuckoohashtablereportedthatmanyofthe standard hashfunctions that
theyattemptedperformedpoorlyintests.Furthermore,althoughtheinsertion timeis
expectedtobeconstanttimeaslongastheloadfactorisbelow
1
2
,theboundthathasbeen
shownfortheexpectedinsertioncostforclassiccuckoohashingwithtwoseparatetables
(bothwithloadfactorλ)isroughly1/(1−(4λ
2
)
1/3
),whichdeterioratesrapidlyasthe
loadfactorgetscloseto
1
2
(theformulaitselfmakesnosensewhenλequalsorexceeds
1
2
).Usinglowerloadfactorsormorethan twohashfunctionsseemslikeareasonable
alternative.
5.7.3 HopscotchHashing
Hopscotchhashingisanewalgorithmthattriestoimproveontheclassiclinearprobing
algorithm.Recallthatinlinearprobing,cellsaretriedinsequentialorder,startingfromthe
hashlocation.Becauseofprimaryandsecondaryclustering,thissequencecanbelongon
averageasthetablegetsloaded,andthusmanyimprovementssuchasquadraticprobing,
doublehashing,andsoforth,havebeenproposedtoreducethenumberofcollisions.
However,onsomemodernarchitectures,thelocalityproducedbyprobingadjacentcells
isamoresignificantfactorthantheextraprobes,andlinearprobingcanstillbepractical
orevenabestchoice.
Theideaofhopscotchhashingistoboundthemaximallengthoftheprobesequence
byapredeterminedconstantthatisoptimizedtotheunderlyingcomputer’sarchitecture.
Doingsowouldgiveconstant-timelookupsintheworstcase,andlikecuckoohashing,the
lookupcouldbeparallelizedtosimultaneouslychecktheboundedsetofpossiblelocations.
Ifaninsertionwouldplaceanewitemtoofarfromitshashlocation,thenweeffi-
cientlygobackwardtowardthehashlocation,evictingpotentialitems.Ifwearecareful,
theevictionscanbedonequicklyandguaranteethatthoseevictedarenotplacedtoofar
fromtheirhashlocations.Thealgorithmisdeterministicinthatgivenahashfunction,
eithertheitemscanbeevictedortheycan’t.Thelattercaseimpliesthatthetableislikely
toocrowded,andarehashisinorder;butthiswouldhappenonlyatextremelyhighload
factors,exceeding0.9.Foratablewithaloadfactorof
1
2
,thefailureprobabilityisalmost
zero(Exercise5.23).
LetMAX_DISTbethechosenboundonthemaximumprobesequence.Thismeans
that item must befound somewhere in the MAX_DIST positions s listed d in hash(x),
hash(x)+1,..., hash(x)+(MAX_DIST−1).Inordertoefficientlyprocessevictions,
wemaintaininformationthattellsforeachpositionx,whethertheiteminthealternate
positionisoccupiedbyanelementthathashestopositionx.
As an example, , Figure 5.46 shows s a a fairly y crowded d hopscotch hash table,using
MAX_DIST = 4.Thebit t array forposition 6showsthatonly position6 has an item
(C)withhashvalue6:OnlythefirstbitofHop[6]isset.Hop[7]hasthefirsttwobits
set,indicatingthatpositions7and8(AandD)areoccupiedwithitemswhosehashvalue
is7.AndHop[8]hasonlythethirdbitset,indicatingthattheiteminposition10(E)has
hashvalue8.IfMAX_DISTisnomorethan32,theHoparrayisessentiallyanarrayof
32-bitintegers,sotheadditionalspacerequirementisnotsubstantial.IfHop[pos]contains
all1sforsomepos,thenanattempttoinsertanitemwhosehashvalueisposwillclearly
228
Chapter5 Hashing
Item
Hop
...
6
C
1000
7
A
1100
8
D
0010
9
B
1000
10
E
0000
11
G
1000
12
F
1000
13
0000
14
0000
...
A:7
B:9
C:6
D:7
E:8
F:12
G:11
Figure5.46 Hopscotchhashingtable.Thehopstellwhichofthepositionsintheblock
areoccupiedwithcellscontainingthishashvalue.ThusHop[8]=0010indicatesthat
onlyposition10currentlycontainsitemswhosehashvalueis8,whilepositions8,9,and
11donot.
fail,sincetherewouldnowbeMAX_DIST+1itemstryingtoresidewithinMAX_DIST
positionsofpos—animpossibility.
Continuingtheexample,supposewenowinsertitemHwithhashvalue9.Ournormal
linearprobingwouldtrytoplaceitinposition13,butthatistoofarfromthehashvalue
of9.Soinstead,welooktoevictanitemandrelocateittoposition13.Theonlycandidates
togointoposition13wouldbeitemswithhashvalueof10,11,12,or13.Ifweexamine
Hop[10],weseethattherearenocandidateswithhashvalue10.ButHop[11]producesa
candidate,G,withvalue11thatcanbeplacedintoposition13.Sinceposition11isnow
closeenoughtothehashvalueofH,wecannowinsertH.Thesesteps,alongwiththe
changestotheHopinformation,areshowninFigure5.47.
Finally,wewillattempt toinsertwhosehash valueis6.Linearprobingsuggests
position14,butofcoursethatistoofaraway.ThuswelookinHop[11],andittellsusthat
Gcanmovedown,freeingupposition13.Nowthat13isvacant,wecanlookinHop[10]
tofindanotherelementtoevict.ButHop[10]hasallzerosinthefirstthreepositions,so
therearenoitemswithhashvalue10thatcanbemoved.SoweexamineHop[11].There
wefindallzerosinthefirsttwopositions.
SowetryHop[12],whereweneedthefirstpositiontobe1,whichitis.ThusFcan
movedown.ThesetwostepsareshowninFigure5.48.Noticethatifthiswerenotthe
case—forinstanceifhash(F)were9insteadof12—wewouldbestuckandhavetorehash.
However,thatisnotaproblemwithouralgorithm;instead,therewouldsimplybenoway
toplaceallofC,I,A,D,E,B,H,andF(ifF’shashvaluewere9);theseitemswouldallhave
hashvaluesbetween6and9,andwouldthusneedtobeplacedinthesevenspotsbetween
6and12.Butthatwouldbeeightitemsinsevenspots—animpossibility.However,since
thisisnotthecaseforourexample,andwehaveevictedanitemfromposition12,wecan
nowcontinue.Figure5.49showstheremainingevictionfromposition9andsubsequent
placementofI.
5.7 HashTableswithWorst-CaseO(1)Access
229
Item
Hop
...
6
C
1000
7
A
1100
8
D
0010
9
B
1000
10
E
0000
11
G
1000
12
F
1000
13
0000
14
0000
...
Item
Hop
...
6
C
1000
7
A
1100
8
D
0010
9
B
1000
10
E
0000
11
0010
12
F
1000
13
G
0000
14
0000
...
Item
Hop
...
6
C
1000
7
A
1100
8
D
0010
9
B
1010
10
E
0000
11
H
0010
12
F
1000
13
G
0000
14
0000
...
A:7
B:9
C:6
D:7
E:8
F:12
G:11
H:9
Figure5.47 Hopscotchhashingtable.AttemptingtoinsertH.Linearprobingsuggests
location13,butthatistoofar,soweevictGfromposition11tofindacloserposition.
Item
Hop
...
6
C
1000
7
A
1100
8
D
0010
9
B
1010
10
E
0000
11
H
0010
12
F
1000
13
G
0000
14
0000
...
Item
Hop
...
6
C
1000
7
A
1100
8
D
0010
9
B
1010
10
E
0000
11
H
0001
12
F
1000
13
0000
14
G
0000
...
Item
Hop
...
6
C
1000
7
A
1100
8
D
0010
9
B
1010
10
E
0000
11
H
0001
12
0100
13
F
0000
14
G
0000
...
A:7
B:9
C:6
D:7
E:8
F:12
G:11
H:9
I:6
Figure5.48 Hopscotchhashingtable.AttemptingtoinsertI.Linearprobing suggests
location14,butthatistoofar;consultingHop[11],weseethatGcanmovedown,leaving
position13open.ConsultingHop[10]givesnosuggestions.Hop[11]doesnothelpeither
(why?),soHop[12]suggestsmovingF.
Hopscotchhashingisarelativelynewalgorithm,buttheinitialexperimentalresultsare
verypromising,especiallyforapplicationsthatmakeuseofmultipleprocessorsandrequire
significantparallelismandconcurrency.Itremainstobeseenifeithercuckoohashingor
hopscotchhashingemergeasapracticalalternativetotheclassicseparatechainingand
linear/quadraticprobingschemes.
230
Chapter5 Hashing
Item
Hop
...
6
C
1000
7
A
1100
8
D
0010
9
B
1010
10
E
0000
11
H
0001
12
0100
13
F
0000
14
G
0000
...
Item
Hop
...
6
C
1000
7
A
1100
8
D
0010
9
0011
10
E
0000
11
H
0001
12
B
0100
13
F
0000
14
G
0000
...
Item
Hop
...
6
C
1001
7
A
1100
8
D
0010
9
I
0011
10
E
0000
11
H
0001
12
B
0100
13
F
0000
14
G
0000
...
A:7
B:9
C:6
D:7
E:8
F:12
G:11
H:9
I:6
Figure5.49 Hopscotchhashingtable.InsertionofIcontinues:Next,Bisevicted,and
finally,wehaveaspotthatiscloseenoughtothehashvalueandcaninsertI.
5.8 UniversalHashing
Although hash tables are very efficient and haveconstant averagecostper operation,
assuming appropriateloadfactors,theiranalysisandperformancedependonthehash
functionhavingtwofundamentalproperties:
1. The e hash function mustbecomputable in constanttime(i.e.,independentofthe
numberofitemsinthehashtable).
2. Thehashfunctionmustdistributeitsitemsuniformlyamongthearrayslots.
Inparticular,ifthehashfunctionispoor,thenallbetsareoff,andthecostperoperation
canbelinear.Inthissection,wediscussuniversalhash functions,whichallowusto
choosethehashfunctionrandomlyinsuchawaythatcondition2aboveissatisfied.As
inSection5.7,weuseMtorepresentTableSize.Althoughastrongmotivationfortheuse
ofuniversalhashfunctionsistoprovidetheoreticaljustificationfortheassumptionsused
intheclassichash tableanalyses,thesefunctionscan alsobeused inapplicationsthat
requireahighlevelofrobustness,inwhichworst-case(orevensubstantiallydegraded)
performance,perhapsbasedoninputsgeneratedbyasaboteurorhacker,simplycannot
betolerated.
AsinSection5.7,weuseMtorepresentTableSize.
Definition5.1
AfamilyHofhashfunctionsisuniversal,ifforanyx=y,thenumberofhashfunctions
hinHforwhichh(x)=h(y)isatmost|H|/M.
Noticethatthisdefinitionholdsforeachpairofitems,ratherthanbeingaveragedover
allpairsofitems.Thedefinitionabovemeansthatifwechooseahashfunctionrandomly
fromauniversalfamilyH,thentheprobabilityofacollisionbetweenanytwodistinctitems
5.8 UniversalHashing
231
isatmost1/M,andwhenaddingintoatablewithNitems,theprobabilityofacollisionat
theinitialpointisatmostN/M,ortheloadfactor.
Theuseofauniversalhashfunctionforseparatechainingorhopscotchhashingwould
besufficienttomeettheassumptionsusedintheanalysisofthosedatastructures.However,
itisnotsufficientforcuckoohashing,whichrequiresastrongernotionofindependence.
Incuckoohashing,wefirstseeifthereisavacantlocation;ifthereisnot,andwedoan
eviction,adifferentitemisnowinvolvedinlookingforavacantlocation.Thisrepeats
untilwefindthevacantlocation,ordecidetorehash[generallywithinO(logN)steps].
In orderfortheanalysistowork,each step must haveacollision probabilityofN/M
independently,withadifferentitemxbeingsubjecttothehashfunction.Wecanformalize
thisindependencerequirementinthefollowingdefinition.
Definition5.2
AfamilyHofhashfunctionsisk-universal,ifforanyx
1
=y
1
,x
2
=y
2
,...,x
k
=y
k
,
thenumberofhashfunctionshinHforwhichh(x
1
)=h(y
1
),h(x
2
)=h(y
2
),...,and
h(x
k
)=h(y
k
)isatmost|H|/Mk.
Withthisdefinition,weseethattheanalysisofcuckoohashingrequiresanO(logN)-
universalhashfunction(afterthatmanyevictions,wegiveupandrehash).Inthissection
welookonlyatuniversalhashfunctions.
Todesignasimpleuniversalhashfunction,wewillassumefirstthatwearemapping
verylargeintegersintosmallerintegersrangingfrom0toM−1.Letpbeaprimelarger
thanthelargestinputkey.
OuruniversalfamilyHwillconsistofthefollowingsetoffunctions,whereaandbare
chosenrandomly:
H={H
a,b
(x)=((ax+b) modp) modM,where1≤ap−1,0≤bp−1}
Forexample,inthisfamily,threeofthepossiblerandomchoicesof(a,b)yieldthree
differenthashfunctions:
H
3,7
(x)=((3x+7)modp)modM
H
4,1
(x)=((4x+1)modp)modM
H
8,0
(x)=((8x)modp)modM
Observethattherearep(p−1)possiblehashfunctionsthatcanbechosen.
Theorem5.4
ThehashfamilyH= {H
a,b
(x)= ((ax+b)modp)modM,where1≤ a≤ p−1,
0≤bp−1}isuniversal.
Proof
Letxandybedistinctvalues,withx>y,suchthatH
a,b
(x)=H
a,b
(y).
Clearlyif(ax+b)modpisequalto(ay+b)modp,thenwewillhaveacollision.
However,thiscannothappen:Subtractingequationsyieldsa(xy) ≡ 0(modp),
whichwouldmeanthatpdividesaorpdividesxy,sincepisprime.Butneithercan
happen,sincebothaandxyarebetween1andp−1.
Soletr=(ax+b)modpandlets=(ay+b)modp,andbytheaboveargument,
r= s.Thusthereareppossiblevaluesforr,andforeachr,therearep−1possible
Documents you may be interested
Documents you may be interested