Untitled

 avatar
Darin
plain_text
a year ago
2.7 kB
3
Indexable
Never
import java.util.*;
 
 
class UserSolution {
    Map<String, TreeSet<String>> mapDir[] = new HashMap[3];
    Map<String, Room> map = new HashMap<>();
    Room current;
 
 
    void init() {
        map.clear();
        for (int i = 0; i < 3; i++)
            mapDir[i] = new HashMap<>();
    }
 
 
    void addRoom(int mID, char mWord[], int mDirLen[]) {
        Room room = new Room(mID, mWord, mDirLen);
        room.addToHash();
    }
 
 
    void setCurrent(char mWord[]) {
        current = map.get(toStr(mWord));
    }
 
 
    int moveDir(int mDir) {
        String prefix = current.dir[mDir];
        if (mapDir[mDir].get(prefix) != null) {
            for (String word : mapDir[mDir].get(prefix)) {
                Room room = map.get(word);
                if (room != current) {
                    current = room;
                    return room.id;
                }
            }
        }
        return 0;
    }
 
 
    void changeWord(char mWord[], char mChgWord[], int mChgLen[]) {
        Room room = map.get(toStr(mWord));
        room.removeFromHash();
        addRoom(room.id, mChgWord, mChgLen);
        if (room == current)
            current = map.get(toStr(mChgWord));
    }
 
 
    String toStr(char[] s) {
        return new String(s).trim();
    }
 
 
    class Room {
        int id;
        String word;
        String dir[] = new String[3];
 
 
        Room(int mID, char mWord[], int mDirLen[]) {
            id = mID;
            word = toStr(mWord);
            dir[0] = word.substring(0, mDirLen[0]);
            dir[1] = word.substring(4, 7);
            dir[2] = word.substring(word.length() - mDirLen[2]);
        }
 
 
        void addToHash() {
            map.put(word, this);
            mapDir[2].computeIfAbsent(word.substring(0, 2), k -> new TreeSet<>()).add(word);
            mapDir[2].computeIfAbsent(word.substring(0, 4), k -> new TreeSet<>()).add(word);
            mapDir[1].computeIfAbsent(word.substring(4, 7), k -> new TreeSet<>()).add(word);
            mapDir[0].computeIfAbsent(word.substring(7), k -> new TreeSet<>()).add(word);
            mapDir[0].computeIfAbsent(word.substring(9), k -> new TreeSet<>()).add(word);
        }
 
 
        void removeFromHash() {
            map.remove(word);
            mapDir[2].get(word.substring(0, 2)).remove(word);
            mapDir[2].get(word.substring(0, 4)).remove(word);
            mapDir[1].get(word.substring(4, 7)).remove(word);
            mapDir[0].get(word.substring(7)).remove(word);
            mapDir[0].get(word.substring(9)).remove(word);
        }
    }
}