[카카오 코테] 가장 많이 받을 선물의 갯수 구하기 ( 원하는 값의 인덱스 추출 )

Loopy·2023년 11월 26일
0

코테 문제들

목록 보기
15/113

✅ 코드

앞의 입력은 단순히 결과 확인을 위해 넣은 데이터이다.
사용했던 코드는 solution 함수안의 코드이다.

import java.util.Arrays;
import java.util.StringTokenizer;

public class Main {
	public static void main(String[] args) {

		String[] friends = new String[4];
		String[] gitts = new String[8];

		friends[0] = "m";
		friends[1] = "r";
		friends[2] = "f";
		friends[3] = "n";


		gitts[0] = "m f";
		gitts[1] = "m f";
		gitts[2] = "r m";
		gitts[3] = "r m";
		gitts[4] = "r m";
		gitts[5] = "f m";
		gitts[6] = "f r";
		gitts[7] = "n m";

		System.out.println(solution(friends, gitts));

	}


	public static int solution(String[] friends, String[] gifts) {
		int answer = 0;
		StringTokenizer st;

		int gift[][] = new int[friends.length][friends.length];
		int giftStock[] = new int[friends.length];
		int count[] = new int[friends.length];

		for (int i = 0; i < gifts.length; i++) {
			String giftName = gifts[i];
			st = new StringTokenizer(giftName);
			String nameA = st.nextToken();
			String nameB = st.nextToken();
			++gift[Arrays.asList(friends).indexOf(nameA)]
            [Arrays.asList(friends).indexOf(nameB)];
		}

		for (int i = 0; i < gift.length; i++) {
			int rowNum = 0, colNum = 0, temp = 0;
			for (int j = 0; j < gift.length; j++) {
				rowNum += gift[i][j];
				colNum += gift[j][i];
			}
			temp = rowNum - colNum;
			giftStock[i] = temp;
		}

		for (int from = 0; from < gift.length; from++) {
			for (int to = 0; to < gift.length; to++) {
				if (from == to) continue;

				if (gift[from][to] > gift[to][from]) {
					count[from]++;
				} else if (gift[from][to] == gift[to][from]) {
					if (giftStock[from] > giftStock[to]) {
						count[from]++;
					} else if (giftStock[to] < giftStock[from]) {
						count[to]++;
					}
				}

			}
		}

		for (int i = 0; i < count.length; i++) {
			answer = Math.max(answer, count[i]);
		}
		return answer;
	}
}




✅ 원하는 인덱스를 추출하는 방법

gift[Arrays.asList(friends).indexOf(nameA)] 
	[Arrays.asList(friends).indexOf(nameB)];

생각보다 원하는 아이디어를 직접 구현하지 않아도 자바가 제공하주는 클래스를 이용하여 간단하게 구현이 가능하다.
사실, 원하는 값이 있는 배열의 인덱스를 추출하기 위해 코드를 직접 구현하고 있었는데 애초에 미리 저런 클래스를 알았더라면 시간을 낭비하지 않아도 됐었다.
다음에는 제공하는 클래스가 있는지 먼저 찾아보도록 하자.


✅ 반복문 변수를 from 과 to 로 선언하자

주고 받은 횟수는 중복이다.
따라서, from == to 라면 continue 로 반복문의 현재 단계를 중단시키자.

for (int from = 0; from < gift.length; from++) {
			for (int to = 0; to < gift.length; to++) {
				if (from == to) continue;

				if (gift[from][to] > gift[to][from]) {
					count[from]++;
				} else if (gift[from][to] == gift[to][from]) {
					if (giftStock[from] > giftStock[to]) {
						count[from]++;
					} else if (giftStock[to] < giftStock[from]) {
						count[to]++;
					}
				}

			}
		}
profile
잔망루피의 알쓸코딩

0개의 댓글