나는 Java에 매우 익숙하며 다음 과제에 매달렸다. 가장 높은 총 ActivityLevel을 가진 Person 객체를 반환하는 AddressBook 클래스에 메소드를 생성하라는 요청을 받았습니다.Java 코드를 어떻게 단순화 할 수 있습니까?
getSocialMediaActivityLevel(), maxValue() 및 findMostSocial() 메소드를 만들었습니다.
findMostSocial 메서드는 내가 수행 한 값을 반환하지만 할당에 대한 설명에는 "간단한 알고리즘을 디자인하고 기존 클래스에 통합해야합니다."라는 문이 포함되어 있습니다. 불필요한 많은 코드를 사용한 것처럼 보이지만, 내가 한 일을 단순화하는 방법을 잘 모르겠습니다. 어떤 도움이라도 대단히 감사합니다.
public class SocialMediaAccount {
private String userID;
private String websiteName;
private String websiteURL;
private int activityLevel;
public SocialMediaAccount(String userID, String websiteName, String websiteURL, int activityLevel) {
this.userID = userID;
this.websiteName = websiteName;
this.websiteURL = websiteURL;
this.activityLevel = activityLevel;
}
public void addSocialMediaAccount(String userID, String websiteName, String websiteURL, int activityLevel) {
SocialMediaAccount account1;
account1 = new SocialMediaAccount(userID, websiteName, websiteURL, activityLevel);
socialMediaAccounts.add(account1);
}
import java.util.ArrayList;
public class Person {
private String firstName;
private String surname;
private String mobile;
private String email;
private ArrayList<SocialMediaAccount> socialMediaAccounts;
//returns the combined ActivityLevel for all the Person's SocialMediaAccounts.
public int getSocialMediaActivityLevel(){
int total = 0;
for(SocialMediaAccount e : socialMediaAccounts){
total += e.getActivityLevel();
}
return total;
}
import java.util.ArrayList;
import java.util.Collections;
public class AddressBook {
private ArrayList<Person> contacts;
public AddressBook(){
contacts = new ArrayList<>();
}
//returns the highest combined ActivityLevel in the ArrayList contacts
public int maxValue(){
ArrayList<Integer> maxActivityLevel = new ArrayList<>();
for(Person e : contacts){
maxActivityLevel.add(e.getSocialMediaActivityLevel());
}
int maxValue = Collections.max(maxActivityLevel);
return maxValue;
}
//returns the Person object in the contacts ArrayList with the highest combined ActivityLevel
public Person findMostSocial(){
for(Person p: contacts){
if(maxValue() == p.getSocialMediaActivityLevel()){
return p;
}
}
return null;
}
max를 계산 한 다음 일치하는 수준의 사람을 검색하는 대신 "연락처"목록을 한 번만 반복하면됩니다. 지금까지 본 최대 활동 수준과 해당 수준의 사람을 모두 추적 할 수 있으며 목록의 다음 연락처가 현재 최고 점수를 "상회"하는 경우에만 업데이트 할 수 있습니다. – CAW
또한 알고리즘을 변경하지 않고도 현재 솔루션에 적용 할 수있는 간단한 개선 사항이 있습니다. 현재 findMostSocial() 메서드 내에서 maxLevel()을 여러 번 계산합니다. 이 작업은 한 번만 수행하고 변수에 값을 저장 한 다음 각 사람의 점수를 비교해야합니다. – CAW