<문제>
1. 중복되는 숫자 개수 구하기
public static void main(String[] args) {
int A = 22;
int B = 456;
int C = 44;
int[] counts = new int[10]; // 나머지가 0~9 이므로 총 10개의 인덱스 필요
int number = A*B*C;
System.out.println("세 정수 곱 : " + number);
while(number>0) {
counts[number%10]++;
// 인덱스는 0부터 시작하므로
// 나머지 값이 1일 경우 두번째 인덱스 값 + 1
// 즉, 나머지 3이 두 번 나오면 4번째 인덱스의 값 2가 됨
number /= 10;
}
for(int i = 0; i<counts.length; i++) {
System.out.println(i + " 개수 : " + counts[i]);
}
}
<실행 결과>
<문제>
2. 주어진 이름 배열중에서 중복되는 성 개수를 구하고, 어떤 성이 제일 많은지 찾아라
Collections.frequency 사용
public static void main(String[] args) {
List<String> list = new ArrayList<>(Arrays.asList("이하나", "이둘", "이셋", "김넷", "박다섯"));
System.out.println("원본 : " + list);
ArrayList<Character> list2 = new ArrayList<>();
for(int i = 0; i<list.size(); i++) {
list2.add(list.get(i).charAt(0));
}
//ArrayList<Character> set = new ArrayList<Character>(list2);
// 중복이 허용되므로 중복허용하지 않는 HashSet으로 변경해줘야함
/*
* 이씨 몇 명 ? 3
이씨 몇 명 ? 3
이씨 몇 명 ? 3
김씨 몇 명 ? 2
박씨 몇 명 ? 1
김씨 몇 명 ? 2
*/
Set<Character> set = new HashSet<Character>(list2);
// ArrayList를 중복이 없는 Collection 객체인 HashSet으로 변경
/*
* 김씨 몇 명 ? 2
이씨 몇 명 ? 3
박씨 몇 명 ? 1
*/
for(Character str : set) {
System.out.println(str + "씨 몇 명 ? " + Collections.frequency(list2, str));
}
System.out.println("가장 많은 성씨는 ? " + Collections.max(list2));
}
<실행결과>