CodeWars 여든 네 번째 문제
Updated:
Weight for weight
public static String orderWeight(String strng) {
if(strng.length() == 0) {
return "";
}
String[] weightSplit = strng.split(" ");
int[] weight = new int[weightSplit.length];
for(int i = 0; i < weightSplit.length; i++) {
weight[i] = convertWeight(weightSplit[i]);
}
selectSort(weight, weightSplit);
return String.join(" " , weightSplit);
}
private static void selectSort(int[] sort, String[] weightSplit) {
for(int i = 0; i < sort.length -1; i++) {
for(int j = i+1; j < sort.length; j++) {
if((sort[i] > sort[j])
|| (sort[i] == sort[j]
&& weightSplit[i].compareTo(weightSplit[j]) > 0)) {
int temp = sort[i];
sort[i] = sort[j];
sort[j] = temp;
String weight = weightSplit[i];
weightSplit[i] = weightSplit[j];
weightSplit[j] = weight;
}
}
}
}
private static int convertWeight(String valueOf) {
int sum = 0;
for(int i = 0; i < valueOf.length(); i++) {
sum += Integer.parseInt(valueOf.substring(i, i+1));
}
return sum;
}
- 정렬하는 기준이 가중치 + 각 문자열에 대한 알파벳순(아스키코드 값)이었다.
- 큰 틀은 Best 코드들과 차이 없었는데 정렬하는 방법이 나는 직접 선택정렬을 만들어서 사용했다. 물론 퀵소트로 하면 더 좋은 성능이겠지만 그것이 중요한 건 아닌 것 같아서 그냥 간단히 만들 수 있는 걸로 했다.
- 그러나 Best 코드의 경우 역시나 Arrays.sort를 사용하는데 오버라이딩하여 수정해서 사용했다.
- 가중치 계산하는 것은 map을 사용했는데 나는 잘 몰라서 내가 만든 메소드 사용해서 나름 수정해봤다.
- 훨씬 깔끔해진 느낌이다. 오버라이딩 잘 사용해야겠다.
public static String orderWeight(String string) {
String[] split = string.split(" ");
Arrays.sort(split, new Comparator<String>() {
public int compare(String a, String b) {
int aWeight = convertWeight(a);
int bWeight = convertWeight(b);
return aWeight - bWeight != 0 ? aWeight - bWeight : a.compareTo(b);
}
});
return String.join(" ", split);
}
private static int convertWeight(String valueOf) {
int sum = 0;
for(int i = 0; i < valueOf.length(); i++) {
sum += Integer.parseInt(valueOf.substring(i, i+1));
}
return sum;
}