Group Algorithm - 그룹 알고리즘
Programming/Java Algorithm 기초

Group Algorithm - 그룹 알고리즘

반응형

1. Group Algorithm - 그룹 알고리즘

package Algorithm;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class GroupAlgorithm {
//[?] 컬렉션 형태의 데이터를 특정 키 값으로 그룹화
//그룹 알고리즘(Group Algorithm) : 특정 키 값에 해당하는 그룹화된 합계 리스트를 만듦

	public static class Record{
		private final String name;	//상품명
		private final int quantity;	//수량
		
		public Record(String name, int quantity) {
			this.name = name;
			this.quantity = quantity;
		}

		public String getName() {
			return name;
		}
		public int getQuantity() {
			return quantity;
		}
	}
	
	//[0][1] 테스트용 데이터 채우기용 로컬 함수
	public static List<Record> getAll(){
		 return Arrays.asList(
				 new Record("RADIO", 3),
				 new Record("TV", 1),
				 new Record("RADIO", 2),
				 new Record("DVD", 4)
				 );
	}
	//[0][2] 컬렉션 데이터 출력용 로컬 함수
	public static void printData(String message, List<Record> data) {
		System.out.println(message);
		for (Record item : data) {
			System.out.println(String.format("%5s - %d", item.getName(), item.getQuantity()));
		}
		
	}
	public static void main(String[] args) {
		//[1] input
		List<Record> records = getAll();	//입력 데이터
		List<Record> groups = new ArrayList<Record>();	//출력 데이터
		int N = records.size(); //의사 코드
		
		
		//[2] process : Group Algorithm (sort -> sum -> group)
		//[A] 그룹 정렬 : SORT
		for (int i = 0; i < N; i++) {
			for (int j = i+1; j < N; j++) {
				if(records.get(i).getName().compareTo(records.get(j).getName()) > 0) {
					Record t = records.get(i);
					records.set(i, records.get(j));
					records.set(j, t);
				}
			}
		}
		
		//[B] 그룹 소계 : GROUP
		int subtotal = 0;	//소계 임시저장
		for (int i = 0; i < N; i++) {
			subtotal += records.get(i).getQuantity();	//같은 상품명의 판매량을 누적(sum)
			if((i + 1) == N ||	//단락(short circuiting)이면 아래 조건 무시.
					(records.get(i).getName() != records.get(i+1).getName())) {
				//[!] 다음 레코드가 없거나, 현재 레코드와 다음 레코드가 다르면 저장.
				Record r = new Record(records.get(i).getName(), subtotal);
				groups.add(r);	//하나의 그룹을 저장
				
				subtotal = 0;	//하나의 그룹이 완료되면 소계 초기화
			}
		}

		
		//[3] output
		printData("[1] 정렬된 원본 데이터: ",records);
		printData("[2] 이름으로 그룹화된 데이터: ",groups);
	}
}

  • 데이터 클래스 Record를 생성한 후
  • List<Record>형 getAll() 로컬 메서드를 생성한다. 이 메서드는 Record형으로 기록된 List<Record>형 데이터를 저장한다.
  • 그리고 printData() 로컬 메서드를 생성한다. 이 메서드는 데이터 출력을 담당.

 

그리고 main()메서드에서는

  • getAll()메서드를 사용해 저장된 데이터를 records 배열에 입력하고, 또 하나의 배열 groups를 생성한다.
  • 원본 데이터(records)를 정렬하는 부분과, 정렬된 데이터를 저장하고, 중복된 데이터는 합하여 groups배열에 저장하는 부분으로 나눠진다.
  • 그리고 printData()메서드를 활용해 두 배열을 비교하기 위해 출력한다.
반응형