#C1057. Organize Books by Genre
Organize Books by Genre
Organize Books by Genre
You are given a list of books. Each book has three attributes: title, author's last name, and genre. Your task is to group the books by their genre and within each genre, sort the books in ascending order by the author's last name.
The result should be output as a JSON object where the keys are the genres and the corresponding values are lists of book objects. Each book object must contain exactly the fields title
and author_last_name
.
Input Format: The first line contains an integer n which is the number of books. Each of the next n lines contains three comma-separated strings representing the title, the author's last name, and the genre respectively.
Output Format: A JSON formatted string representing a dictionary mapping each genre to a sorted list of books. Sorting within each genre should be performed in ascending order based on the author's last name.
The approach can be described mathematically as follows:
\[ \text{result}[genre] = \text{sort}_{\text{by } author\_last\_name}(\{\text{book} : book.genre = genre\}) \]inputFormat
The input is given from stdin in the following format:
n book_1_title,book_1_author_last_name,book_1_genre book_2_title,book_2_author_last_name,book_2_genre ... book_n_title,book_n_author_last_name,book_n_genre
Where n
represents the number of books.
outputFormat
The output should be printed to stdout as a single JSON object. The keys of the object are genres, and the values are lists of book objects (each with title
and author_last_name
), sorted by author's last name in ascending order.
4
Book A,Smith,Fiction
Book B,Doe,Non-fiction
Book C,Brown,Fiction
Book D,Black,Non-fiction
{"Fiction": [{"title": "Book C", "author_last_name": "Brown"}, {"title": "Book A", "author_last_name": "Smith"}], "Non-fiction": [{"title": "Book D", "author_last_name": "Black"}, {"title": "Book B", "author_last_name": "Doe"}]}