Untitled
Darin
plain_text
2 years ago
3.6 kB
8
Indexable
Cho đoạn code bên dưới, giải thích thuộc tính Message message; trong class Message dùng để làm gì.
Giải thích mục đích của đoạn code: comment.message = target.message != null ? target.message : target; trong hàm commentTo
class UserSolution {
Map<String, User> users = new HashMap<>();
Map<Integer, Message> messages = new HashMap<>();
TreeSet<User> topUsers = new TreeSet<>((a, b) -> a.point == b.point ? a.name.compareTo(b.name) : b.point - a.point);
TreeSet<Message> topMessages = new TreeSet<>((a, b) -> a.total == b.total ? a.id - b.id : b.total - a.total);
void init() {
users.clear();
messages.clear();
topUsers.clear();
topMessages.clear();
}
int writeMessage(char[] mUser, int mID, int mPoint) {
String name = new String(mUser).trim();
User user = users.computeIfAbsent(name, k -> new User());
user.name = name;
topUsers.remove(user);
user.point += mPoint;
topUsers.add(user);
Message message = new Message(user, mID, mPoint);
messages.put(mID, message);
topMessages.add(message);
return user.point;
}
int commentTo(char[] mUser, int mID, int mTarget, int mPoint) {
writeMessage(mUser, mID, mPoint);
Message target = messages.get(mTarget);
Message comment = messages.get(mID);
comment.message = target.message != null ? target.message : target;
topMessages.remove(comment);
target.comments.add(comment);
topMessages.remove(comment.message);
comment.message.total += mPoint;
topMessages.add(comment.message);
return comment.message.total;
}
int erase(int mID) {
Message post = messages.get(mID);
if (post.message != null) { // comment
topMessages.remove(post.message);
remove(post);
topMessages.add(post.message);
return post.message.total;
} else { // message
topMessages.remove(post);
remove(post);
return post.user.point;
}
}
void remove(Message post) {
for (Message i : post.comments)
if (i.isAlive)
remove(i);
post.isAlive = false;
topUsers.remove(post.user);
post.user.point -= post.point;
topUsers.add(post.user);
if (post.message != null) // comment
post.message.total -= post.point;
}
void getBestMessages(int[] mBestMessageList) {
int i = 0;
for (Message message : topMessages) {
mBestMessageList[i] = message.id;
if (++i == 5)
break;
}
}
void getBestUsers(char[][] mBestUserList) {
int i = 0;
for (User user : topUsers) {
int j;
for (j = 0; j < user.name.length(); j++)
mBestUserList[i][j] = user.name.charAt(j);
mBestUserList[i][j] = '\0';
if (++i == 5)
break;
}
}
}
class User {
String name;
int point;
}
class Message {
User user;
int id, point, total;
boolean isAlive = true;
Message message;
List<Message> comments = new ArrayList<>();
Message(User mUser, int mID, int mPoint) {
user = mUser;
id = mID;
total = point = mPoint;
}
}Editor is loading...