A
download Trie.java
Language: Java
LOC: 570
Project Info
Key - a Java MOO / talker(key)
Server: SourceForge
Type: cvs
...k\key\key\key\src\key\util\
   ArrayEnumeration.java
   Bits.java
   CircularBuffer.java
   EmptyEnumeration.java
   FilteredEnumeration.java
   HTUU.java
   Ident.java
   LinkedList.java
   MultiEnumeration.java
   Queue.java
   RecursiveEnumeration.java
   SeperatedIdentifier.java
   SMTP.java
   StringTokenizer.java
   Trie.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
/*
**               j###t  ########## ####   ####
**              j###t   ########## ####   ####
**             j###T               "###L J###"
**          ######P'    ##########  #########
**          ######k,    ##########   T######T
**          ####~###L   ####
**          #### q###L  ##########   .#####
**          ####  \###L ##########   #####"
**
**  $Id: Trie.java,v 1.1.1.1 1999/10/07 19:58:40 pdm Exp $
**
**  Class History
**
**  Date        Name         Description
**  ---------|------------|-----------------------------------------------
**  19Aug98     subtle       start of recorded history
**
*/

package key.util;

import key.NonUniqueKeyException;
import key.BadKeyException;

import java.net.*;
import java.io.*;
import java.util.*;

/**
  *  The only thing that can't be stored in a
  *  Trie safely is another Trie - we use
  *  instanceof to determine if a Trie is
  *  terminated or not
 */
public final class Trie
{
	static final int BRANCHES = 26;
	
		//  Information about the location of this Trie in the
		//  trie tree ;)
	int position;
	Trie previous;
	
		//  For when a string ends on this trie
	TrieEntry at;
	
		//  The contents of this trie
	Object entries[];
	
	/**
	  * Creates a new trie with no entries
	 */
	public Trie()
	{
		entries = new Object[BRANCHES];
		at = null;
		position = 0;
		previous = null;
	}

		//  Internal constructor
	private Trie( Trie parent )
	{
		this();
		
		previous = parent;
		position = previous.getPosition() + 1;
	}
	
	String spaces()
	{
		StringBuffer s = new StringBuffer();

		for( int i=0; i < position; i++ )
			s.append( " " );
		
		return( s.toString() );
	}

	/**
	  *  Counts the number of linked objects off this trie
	 */
	public int length()
	{
		int count = 0;

		if( at != null )
			count++;

		for( int i=0; i < BRANCHES; i++ )
		{
			if( entries[i] != null )
			{
				if( entries[i] instanceof TrieEntry )
					count++;
				else
					count += ((Trie)entries[i]).length();
			}
		}
	
		return( count );
	}

	/**
	  *  Removes the object with the given key from the
	  *  trie
	 */
	public void remove( String key ) throws NonUniqueKeyException,java.util.NoSuchElementException,BadKeyException
	{
		if( key.length() == position )
		{		//  item is on the 'at' for this trie
			if( at != null )
			{
				at = null;
				return;
			}
			else
				throw new NonUniqueKeyException( key );
		}
		else
		{
			int i = index( key.charAt( position ) );
			
			if( entries[i] != null )
			{
				if( entries[i] instanceof Trie && (((Trie)entries[i]).previous == this) )
				{
					((Trie)entries[i]).remove( key );
					int a = ((Trie)entries[i]).length();
					if( a == 1 )
					{		//  lower trie is now not required
						TrieEntry t = ((Trie)entries[i]).firstElement();
						if( t != null )
						{
							//System.out.println( spaces() + "removing trie with item '" + t.getKey() + "' swapup..." );
							entries[i] = t;
						}
						else
							entries[i] = null;
					}
				}
				else
				{
					entries[i] = null;
					return;
				}
			}
			else
				throw new java.util.NoSuchElementException( key );
		}
	}

	/**
	  * Inserts the provided object into the trie
	  * with the given key.
	 */
	public void insert( String key, Object item ) throws NonUniqueKeyException,BadKeyException
	{
		if( key.length() == position )
		{		//  this item needs to be inserted _on_ this trie
			if( at != null )
				throw new NonUniqueKeyException( key );
			at = new TrieEntry( key, item );
		}
		else
		{
			int i = index( key.charAt( position ) );
			
			if( entries[i] != null )
			{		//  already an item here
				if( entries[i] instanceof Trie && (((Trie)entries[i]).previous == this) )
				{
					//System.out.println( spaces() + "passdown insert" );
					((Trie) entries[i]).insert( key, item );
					return;
				}
				else
				{		//  already something here - create a new
						//  trie, insert this something, and insert
						//  the new something
					if( ((TrieEntry)entries[i]).getKey().equals( key ) )
						throw new NonUniqueKeyException( key );
					
					//System.out.println( spaces() + "item already in place" );
					Trie down = new Trie( this );
					
					//System.out.println( spaces() + "re-inserting " +
					//	((TrieEntry)entries[i]).getKey() ); 

					down.insert( ((TrieEntry)entries[i]).getKey(),
						((TrieEntry)entries[i]).getEntry() );
					
					//System.out.println( spaces() + "inserting " + key );
					down.insert( key, item );

					//System.out.println( spaces() + "updating the new trie for insertion" );
					entries[i] = down;
				}
			}
			else
			{		//  the space is empty - simply add it in
				entries[i] = new TrieEntry( key, item );
				//System.out.println( spaces() + "straight insert of " + key );
			}
		}
	}

	/**
	  * searchExact does *not* return a Trie for 'multiple matches',
	  * but will return null in that case.
	 */
	public Object searchExact( String key )
	{
		if( key.length() == position )
		{		//  check at
			if( at != null )
			{		//  this must be it
				return( at.getEntry() );
			}
			else
			{		//  multiple matches in this case
				return( null );
			}
		}
		int i = 0;
		
		i = negIndex( key.charAt( position ) );
		if( i == -1 )
		{		//  act as if this was the end of the
				//  string - return the at, if there is one
			if( at != null )
				return( at.getEntry() );
			else
				return( null );
		}

		if( entries[i] != null )
		{
			if( entries[i] instanceof Trie )
			{		//  pass it along the chain
				return( ((Trie)entries[i]).searchExact( key ) );
			}
			else
			{		//  found it
						//  some interesting behaviour here - if
						//  the next character is an invalid, there
						//  isn't much chance the key is correct - we'll
						//  treat it as if it was the end of the string (as
						//  per the position == key.length() code above
						//
						//  this little 'hack' is not required for a normal
						//  search, which will find the element as soon as
						//  it has a non-conflicting match
				if( ( position + 1 ) < key.length() )
				{
					if( negIndex( key.charAt( position + 1 ) ) == -1 && key.substring( 0, position+1 ).equalsIgnoreCase( ((TrieEntry)entries[i]).getKey() ) )
						return( ((TrieEntry)entries[i]).getEntry() );
				}
				
				if( key.equalsIgnoreCase( ((TrieEntry)entries[i]).getKey() ) )
					return( ((TrieEntry)entries[i]).getEntry() );
				else
					return( null );
			}
		}
		else
			return( null );
	}

	/**
	  *  Returns a Trie of all the elements starting with
	  *  'key', or an Object which is a single exact match
	 */
	public Object getTrieFor( String key )
	{
		if( key.length() == position )
		{
			return( this );
		}
		int i = 0;
		
		i = negIndex( key.charAt( position ) );
		if( i == -1 )
			return( this );

		if( entries[i] != null )
		{
			if( entries[i] instanceof Trie )
			{		//  pass it along the chain
					return( ((Trie)entries[i]).getTrieFor( key ) );
			}
			else
			{
				if( ((TrieEntry)entries[i]).getKey().startsWith( key.toLowerCase() ) )
					return( ((TrieEntry)entries[i]).getEntry() );
			}
		}
		
		return( null );
	}
	
	/**
	  *  Returns a trie for multiple matches,
	  *  else returns null for no object matched,
	  *  or returns the object matched.  could
	  *  easily be optimised
	 */
	public Object search( String key )
	{
		if( key.length() == position )
		{		//  check at
			if( at != null )
			{		//  this must be it
				return( at.getEntry() );
			}
			else
			{		//  multiple matches in this case
				return( this );
			}
		}
		int i = 0;
		
		i = negIndex( key.charAt( position ) );
		if( i == -1 )
		{		//  act as if this was the end of the
				//  string - return the at, if there is one
			if( at != null )
				return( at.getEntry() );
			else
				return( null );
		}

		if( entries[i] != null )
		{
			if( entries[i] instanceof Trie )
			{		//  pass it along the chain
				return( ((Trie)entries[i]).search( key ) );
			}
			else
			{		//  found it (this check may not be required?)
				if( ((TrieEntry)entries[i]).getKey().startsWith( key.toLowerCase() ) )
					return( ((TrieEntry)entries[i]).getEntry() );
				else
					return( null );
			}
		}
		else
			return( null );
	}


	/**
	  *  From a number between 0 and 25 returns
	  *  the alpha equivalent (between a and z)
	  *
	  * @see index
	 */
	static char letter( int i )
	{
		return( (char) (i + 'a') );
	}

	/**
	  *  Converts a letter between a and z to a number
	  *  between 0 and 25
	  *
	  * @see letter
	 */
	public static final int index( char c ) throws BadKeyException
	{
		int r = negIndex( c );
		if( r == -1 )
			throw new BadKeyException( c );	
		
		return( r );
	}

	/**
	  *  Returns -1 on an error as opposed to throwing an 
	  *  exceptions (exceptions are slow and ugly)
	 */
	public static final int negIndex( char c )
	{
		int r = java.lang.Character.toLowerCase( c ) - 'a';
		if( r < 0 || r > 25 )
			return( -1 );
		else
			return( r );
	}

	/**
	  *  Returns the first element in a trie -
	  *  is generally only used when an element
	  *  is erased from the trie and a trie delete
	  *  and swapup is required.
	 */
	TrieEntry firstElement()
	{
		if( at != null )
			return at;
		
		for( int i = 0; i < BRANCHES; i++ )
			if( entries[i] != null && !(entries[i] instanceof Trie && (((Trie)entries[i]).previous == this)) )
				return ((TrieEntry)entries[i]);
		
		return( null );
	}


	/**
	  *  Returns the character offset that this
	  *  trie is off the main trie
	 */
	int getPosition()
	{
		return( position );
	}

	/**
	  *  Returns an alphabetically sorted list of
	  *  the elements in this trie.  This routine
	  *  is rather inefficient.
	 */
	public Enumeration elements()
	{
		Vector v = new Vector( 30, 20 );

		elements( v );

		return( v.elements() );
	}
	
	/**
	  *  Returns an alphabetically sorted list of
	  *  the elements in this trie
	 */
	public LinkedList getSortedList()
	{
		LinkedList ll = new LinkedList();
		
		listElements( ll );
		
		return( ll );
	}
	
	/**
	  *  Recursive function to append elements
	  *  to a linked list
	 */
	protected void listElements( LinkedList ll )
	{
		if( at != null )
			ll.append( at.getEntry() );
		
		for( int i=0; i<BRANCHES; i++ )
		{
			if( entries[i] != null )
			{
				if( entries[i] instanceof Trie && (((Trie)entries[i]).previous == this) )
				{
					((Trie)entries[i]).listElements( ll );
				}
				else
					ll.append( ((TrieEntry)entries[i]).getEntry() );
			}
		}
	}
	
	/**
	  *  Recursive function to append elements
	  *  to a linked list
	 */
	protected void elements( Vector v )
	{
		if( at != null )
			v.addElement( at.getEntry() );

		for( int i=0; i<BRANCHES; i++ )
		{
			if( entries[i] != null )
			{
				if( entries[i] instanceof Trie && (((Trie)entries[i]).previous == this) )
				{
					((Trie)entries[i]).elements( v );
				}
				else
					v.addElement( ((TrieEntry)entries[i]).getEntry() );
			}
		}
	}
	
	/**
	  *  This is a simple little test routine
	  *  included so this class can be run as
	  *  an application to test its cababilities
	 */
	public static void main( String args[] )
	{
		Trie main = new Trie();
		String entry;
		int count=0;

		do
		{
			System.out.println( "\nTrie contains " + main.length() + " elements" );
			entry = input( "dump,quit,add,search,delete,avg,num: " );
			if( entry.length() == 0 )
			{
			}
			else if( entry.equals( "avg" ) )
			{
				System.out.println( "\nAverage clash: " + Float.toString( main.averageClash() ) + "\n" );
			}
			else if( entry.equals( "num" ) )
			{
				System.out.println( "\nTotal number of tries: " + main.numberTries() + "\n" );
			}
			else if( entry.equals( "dump" ) )
			{
				System.out.println( "\nDUMPING:\n--------" );
				main.dump();
			}
			else if( entry.startsWith( "search " ) )
			{
				entry = entry.substring( 7 );
				System.out.println( "Searching for " + entry + "..." );
				Object r=null;
				r = main.search( entry );
				if( r == null )
				{
					System.out.println( "Not found" );
				}
				else if( r instanceof Trie )
				{
					System.out.println( "Multiple matches:" );
					((Trie)r).quickDump();
				}
				else
				{
					System.out.println( "Found. Value is " + r.toString() );
				}
			}
			else if( entry.equals( "quit" ) )
			{
			}
			else if( entry.startsWith( "delete " ) )
			{
				entry = entry.substring( 7 );
				System.out.println( "Deleting " + entry + "..." );
				try
				{
					main.remove( entry );
				}
				catch( java.util.NoSuchElementException e )
				{
					System.out.println( e.toString() );
				}
				catch( NonUniqueKeyException e )
				{
					System.out.println( e.toString() );
				}
				catch( BadKeyException e )
				{
					System.out.println( e.toString() );
				}
			}
			else if( entry.startsWith( "add " ) )
			{
				entry = entry.substring( 4 );
				System.out.println( "Inserting " + entry + "..." );
				try
				{
					main.insert( entry, new java.lang.Integer( count++ ) );
				}
				catch( BadKeyException e )
				{
					System.out.println( e.toString() );
				}
				catch( NonUniqueKeyException e )
				{
					System.out.println( e.toString() );
				}
			}
			else
			{
				System.out.println( "Unknown command '" + entry + "'" );
			}
		} while( !entry.equals( "quit" ) );
	}
	
	public static String input( String prompt )
	{
		StringBuffer buildInput = new StringBuffer();
		char b=' ';

		System.out.print( prompt );
		System.out.flush();

		do
		{
			try
			{
				b = (char) System.in.read();
			}
			catch( java.io.IOException e )
				{
						//  generally an IOException here means that
						//  the player in question has disconnected
					System.out.println( e.toString() );
					System.exit( 1 );
				}
			if( b != '\n' && b != 0 )
				buildInput.append( b );
		} while( b != '\n' && b != 0 );

		return( new String( buildInput ) );
	}
	
	public String toString()
	{
		if( length() > 20 )
			return( "Multiple matches: <too many to list (>20)>" );
		else
			return( "Multiple matches: " + contents( new StringBuffer() ) );
	}
	
	public String contents()
	{
		return( contents( new StringBuffer() ) );
	}

	public String contents( StringBuffer b )
	{
		if( at != null )
		{
			b.append( at.getKey() );
			b.append( " " );
		}

		for( int i=0; i<BRANCHES; i++ )
		{
			if( entries[i] != null )
			{
				if( entries[i] instanceof Trie && (((Trie)entries[i]).previous == this) )
				{
					b.append( ((Trie)entries[i]).contents() );
				}
				else
				{
					b.append( ((TrieEntry)entries[i]).getKey() );
					b.append( " " );
				}
			}
		}
		return( b.toString() );
	}

	void quickDump()
	{
		if( at != null )
			System.out.print( at.getKey() + " " );

		for( int i=0; i<BRANCHES; i++ )
		{
			if( entries[i] != null )
			{
				if( entries[i] instanceof Trie && (((Trie)entries[i]).previous == this) )
				{
					((Trie)entries[i]).quickDump();
				}
				else
					System.out.print( ((TrieEntry)entries[i]).getKey() + " " );
			}
		}
	}

	void dump()
	{
		String pre = spaces();
		if( at != null )
			System.out.println( pre + at.getKey() );

		for( int i=0; i<BRANCHES; i++ )
		{
			if( entries[i] != null )
			{
				if( entries[i] instanceof Trie && (((Trie)entries[i]).previous == this) )
				{
					System.out.println( pre + "[" + letter( i ) + "]" );
					((Trie)entries[i]).dump();
				}
				else
					System.out.println( pre + ((TrieEntry)entries[i]).getKey() );
			}
		}
	}

	void averageClash( TrieAverage t )
	{
		if( at != null )
			t.add( position );

		for( int i=0; i<BRANCHES; i++ )
		{
			if( entries[i] != null )
			{
				if( entries[i] instanceof Trie && (((Trie)entries[i]).previous == this) )
				{
					((Trie)entries[i]).averageClash( t );
				}
				else
					t.add( position );
			}
		}
	}

	float averageClash()
	{
		TrieAverage t = new TrieAverage();
		averageClash( t );
		return( ((float) t.average) / ((float)t.number) );
	}
	
	int numberTries()
	{
		int accum = 1;
		
		for( int i=0; i<BRANCHES; i++ )
		{
			if( entries[i] != null )
			{
				if( entries[i] instanceof Trie && (((Trie)entries[i]).previous == this) )
					accum += ((Trie)entries[i]).numberTries();
			}
		}
		
		return( accum );
	}
}

class TrieAverage
{
	int average;
	int number;

	public TrieAverage()
	{
	}

	public void add( int i )
	{
		average += i;
		number++;
	}
}

/**
  *  A private class which is used to
  *  internally mark off elements to
  *  items
 */
class TrieEntry implements Serializable
{
	String key;
	Object entry;

	public TrieEntry()
	{
		key = "";
		entry = null;
	}

	public TrieEntry( String trigger, Object store )
	{
		key = trigger.toLowerCase();
		entry = store;
	}

	public String getKey()
	{
		return( key );
	}

	public Object getEntry()
	{
		return( entry );
	}
}

About Koders | Resources | Downloads | Support | Black Duck | Submit Project | Terms of Service | DMCA | Privacy Policy | Site Map| Contact Us