01204212/spreadsheet

จาก Theory Wiki
ไปยังการนำทาง ไปยังการค้นหา
This is part of 01204212

Examples

> A10=5
> B10=20
> A12=30
> A10
5
> B12345=12345
> B12345
12345
> quit

Code

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

public class Main {

	Map<Integer,Integer> table;
	
	public static void main(String[] args) throws IOException {
		Main m = new Main();
		
		m.process();
	}

	Main() {
		table = new HashMap<Integer, Integer>();
	}
	
	private void process() throws IOException {
	    BufferedReader reader = new BufferedReader(
	               new InputStreamReader(System.in) );

	    System.out.println("Hello!");
	    while(true) {
	    	System.out.print("> ");
	    	String cmd = reader.readLine();
	    	
	    	if(cmd.equals("quit")) {
	    		return;
	    	}
	    	
	    	if(cmd.contains("=")) {
	    		String[] items = cmd.split("=");
	    		int cellNum = getCellNumber(items[0]);
	    		int val = Integer.parseInt(items[1]);
	    		
	    		table.put(cellNum, val);
	    	} else {
	    		int cellNum = getCellNumber(cmd);
	    		
	    		Integer val = table.get(cellNum);
	    		
	    		if(val == null) {
	    			val = 0;
	    		}
	    		System.out.println(val);
	    	}
	    }
	}

	private int getCellNumber(String location) {
		location = location.toUpperCase();
		try {
			int colNum = 0;
			int i = 0;
			while((location.charAt(i) >= 'A') &&
					(location.charAt(i) <= 'Z')) {
				colNum = colNum * 26 + (location.charAt(i) - 'A');
				i++;
			}
			String rowStr = location.substring(i);
			int rowNum = Integer.parseInt(rowStr);
			return colNum * 1000000 + rowNum;
		} catch(Exception e) {
			return -1;
		}
	}
}

Hash table (linear probing)

public class HashTable {
	static final int M = 1000;
	static final int P = 997;
	static final int EMPTY_KEY = -1;
	
	int [] values;
	int [] keys;
	
	public HashTable() {
		values = new int[M];
		keys = new int[M];
		for(int i=0; i<M; i++) {
			keys[i] = EMPTY_KEY;
		}
	}
	
	int hash(int key) {
		return key % P;
	}
	
	void put(int k, int v) {
		int idx = hash(k); 
		//System.out.println("H = " + idx);
		while(keys[idx] != EMPTY_KEY) {
			idx++;
			if(idx == M) {
				idx = 0;
			}
			//System.out.println("Not empty move to " + idx);
		}
		keys[idx] = k;
		values[idx] = v;
	}
	
	int get(int k) {
		int idx = hash(k);
		//System.out.println("H = " + idx);
		while((keys[idx] != k) && (keys[idx] != EMPTY_KEY)) {
			idx++;
			if(idx == M) {
				idx = 0;
			}
			//System.out.println("Not the key, move to " + idx);
		}
		if(keys[idx] == k) {
			return values[idx];
		} else {
			throw new RuntimeException("Sorry");
		}
	}
}