import java.util.*;

public class Hasher1
/* Example of linear probing
 * places keys in table and retreives them
 *
 */
{
	public static void main(String[] asd)
	{
		ConsoleReader kbd = new ConsoleReader();
		System.out.println("Type your keys");
		String s = kbd.readLine();
		StringTokenizer toke = new StringTokenizer(s);
		int key;
		Hash hash = new Hash();
		while(toke.hasMoreTokens() )
		{
			key = Integer.parseInt(toke.nextToken());
			if(!hash.vacancy() )
			{
				System.out.println("No more room in the inn!");
				System.exit(0);
			}
			hash.put(key);
		}
		String ans;
		boolean valid;
		do
		{
			System.out.println("type your key");
			s = kbd.readLine();
			key = Integer.parseInt(s);
			hash.get(key);
			System.out.println("Continue?(Y/N)");
			ans = kbd.readLine();
			ans = ans.toUpperCase();
			valid = false;
			while(!valid)
			{
				valid = ans.equals("Y") || ans.equals("N");
				if(!valid)
				{
					System.out.println("Please retype");
					ans = kbd.readLine();
			        ans = ans.toUpperCase();
			    }
			}				
		}
		while(ans.equals("Y") );
	}
}

class Hash
{
	final static int CAP = 10;
	final int MAX;
	int[] x;
	
	public Hash()
	{
		this(CAP);
	}
	
	
	public Hash(int n)
	{
		MAX = n;
		x = new int[MAX];
		for(int j = 0; j < MAX; j++)
		{
			x[j] = 0;
		}
	}
			
	public boolean vacancy()
	{
		boolean empty = false;
		for(int j = 0; j < MAX; j++)
		{
			empty = empty ||x[j] ==0;
		}
		return empty;
	}
	
	private int hash(int key)
	{
		int j = key % MAX;
		return j;
	}
	
	private int rehash(int j)
	{
		if( j == MAX -1)
		{
			j = 0;
		}
		else
		{
			j++;
		}
		return j;
	}
	
	public void put(int key)
	{	
	    boolean found = false;
		int j = hash(key);
		while(!found)//see if slot j is available
		{
			found = x[j] == 0;//slot found
			if( !found )
			{
				j = rehash(j);
			}
		}
		System.out.println("inserting "+ key + " in slot " +j);
		x[j] = key;
		write();
	}
	
	public void write()
	{
		for(int j = 0; j < MAX; j++)
		{
			System.out.print(x[j] + " ");
		}
		System.out.println();
	}
	public void get(int key)
	{
		boolean found = false;
		int j, count = 0;
//incremented each time loop is executed
		while(!found && count < MAX)
		{
			j = hash(key);
			found = key == x[j];
			if(!found )
			{
				j = rehash(j);
			}
			count++;
		}
		if(found)
		{
			System.out.println(key + " is in table");
		}
		else
		{
			System.out.println(key + " is not in table");
		}			
	}
}
		
		
	
			

