// Arup Guha
// 4/15/2026
// Sample Quiz 4 Question: EscapeRoom Class

import java.io.*;
import java.util.*;

public class EscapeRoom {

	// Instance variables - first stores all the rooms, second maps rooms
	// to a set of each person assigned to that room.
	private ArrayList<String> rooms;
	private HashMap<String, HashSet<String>> assignments;
	
	public EscapeRoom(String filename) throws IOException {
	
		// Open file, read in # of people in the rooms.
		Scanner fin = new Scanner(new File(filename));
		int n = fin.nextInt();
		
		// Instantiate instance variables
		rooms = new ArrayList<String>();
		assignments = new HashMap<String, HashSet<String>>();
		
		// Add each person.
		for (int i=0; i<n; i++) {
		
			// Get next person room mapping.
			String person = fin.next();
			String room = fin.next();
			
			// New room add to our object.
			if (!assignments.containsKey(room)) {
				rooms.add(room);
				assignments.put(room, new HashSet<String>() );
			}
			
			// Add to room.
			assignments.get(room).add(person);
		}
		
		// Close the file.
		fin.close();
	}
	
	// Returns all the people in room in this EscapeRoom in the form
	// of a String array of names of the people. Returns null if there
	// is no room with the name room in this EscapeRoom object.
	public String[] getAllPeople(String room) {
		
		// Get this out of the way.
		if (!assignments.containsKey(room)) return null;
		
		// Set I am getting people from.
		HashSet<String> tmp = assignments.get(room);
		
		// Store result here.
		String[] res = new String[tmp.size()];
		
		// Index into the array.
		int i = 0;
		
		// Go through each item in the set.
		for (String p: tmp) {
			res[i] = p;
			i++;
		}
		
		// Return array.
		return res;
	}
	
	// Testing code.
	public static void main(String[] args) {
		
		// Ask the user to enter a file name.
		Scanner stdin = new Scanner(System.in);
		System.out.println("enter file.");
		String file = stdin.next();
		
		// We do a try-catch to catch the IOException just in case
		// their file isn't valid.
		try {
			
			// Try creating the object.
			EscapeRoom mine = new EscapeRoom(file);
			
			// Ask the user for a room.
			System.out.println("enter room.");
			String room = stdin.next();
			
			// Get who is there.
			String[] ans = mine.getAllPeople(room);
			
			// Safe to print do so.
			if (ans != null) {
				for (String person: ans)
					System.out.println(person);
			}
			
			// Print error message.
			else {
				System.out.println("not a room.");
			}
				
		} 
		
		// Here we catch the IOException so a bad file doesn't crash the program.
		catch (IOException e) {
			
			// We just print this error message.
			System.out.println("file not found.");
		}
	}
}