Re: HashMap vs linear table lookup
Lord Zoltar <lord.zoltar@gmail.com> writes:
It would probably also be possible to write your own hash function,
Here is an example, using a lookup indexed by the final
two letters of the month TLA. (This might actually be a
perfect hash, I am not sure about this.)
A small table might be used instead of the ?switch? in ?show?.
This is no hash map, but a direct array look up by a special
hash function, I believe O(1).
public class Main
{
int[] v;
public Main()
{ v = new int[ 256 ]; for( int i = 0; i < 256; ++i )v[ i ]=15;
v[ 97 ]= 0; v[ 98 ]= 9; v[ 99 ]= 4; v[ 101 ]= 2; v[ 103 ]= 9;
v[ 108 ]= 8; v[ 110 ]= 2; v[ 111 ]= 4; v[ 112 ]= 3; v[ 114 ]= 1;
v[ 116 ]= 3; v[ 117 ]= 1; v[ 118 ]= 4; v[ 121 ]= 0; }
int hash( final java.lang.String s )
{ return v[ s.charAt( 1 )]+v[ s.charAt( 2 )] ; }
void show( final java.lang.String s )
{ switch ( hash( s ))
{ case 4: case 3: case 5: case 8:
java.lang.System.out.println( 30 ); break;
case 11: break;
default: java.lang.System.out.println( 31 ); break; }}
public static void main( final java.lang.String[] args )
{ new Main().show( "Jun" ); new Main().show( "Oct" ); }}
It prints:
30
31