26-java - 배열 문제들

jin·2022년 7월 2일
0

1. 이차원 배열 기본 문제1


int[][] arr = new int[3][3];

int k = 1;
for (int i = 0; i < 3; i++) {
	for (int j = 0; j < 3; j++) {
		arr[i][j] = 10 * k;
		k += 1;
	}
}
for (int i = 0; i < arr.length; i++) {
	System.out.println(Arrays.toString(arr[i]));
}
System.out.println();
// 문제 1) 전체 합 출력
// 정답 1) 450
int sum = 0;
for (int i = 0; i < arr.length; i++) {
	for (int j = 0; j < arr[i].length; j++) {
		sum += arr[i][j];
	}
}
System.out.println("문제1 : "+sum);
System.out.println();
// 문제 2) 4의 배수만 출력
// 정답 2) 20 40 60 80
System.out.print("문제2 : ");
for (int i = 0; i < arr.length; i++) {
	for (int j = 0; j < arr[i].length; j++) {
		if (arr[i][j] % 4 == 0) {
			System.out.print(arr[i][j] + " ");
		}
	}
}
System.out.println("\n");
// 문제 3) 4의 배수의 합 출력
// 정답 3) 200
sum = 0;
for (int i = 0; i < arr.length; i++) {
	for (int j = 0; j < arr[i].length; j++) {
		if (arr[i][j] % 4 == 0) {
			sum += arr[i][j];
		}
	}
}
System.out.println("문제3 : " + sum);
System.out.println();
// 문제 4) 4의 배수의 개수 출력
// 정답 4) 4
int count = 0;
for (int i = 0; i < arr.length; i++) {
	for (int j = 0; j < arr[i].length; j++) {
		if (arr[i][j] % 4 == 0) {
			count++;
		}
	}
}
System.out.println("문제4 : " + count);

2. 이차원 배열 기본 문제2

Scanner sc = new Scanner(System.in);
int[][] arr = new int[3][3];

int k = 1;
for (int i = 0; i < 3; i++) {
	for (int j = 0; j < 3; j++) {
		arr[i][j] = 10 * k;
		k += 1;
	}
}
for (int i = 0; i < arr.length; i++) {
	System.out.println(Arrays.toString(arr[i]));
}
// 문제1) 인덱스 2개를 입력받아 값 출력
// 예1) 인덱스1 입력 : 1	인덱스2 입력 : 2
//		   값 출력 : 60 
//		System.out.print("첫번째 인덱스 : ");
//		int index1 = sc.nextInt();
//		System.out.print("두번째 인덱스 : ");
//		int index2 = sc.nextInt();
// 더하는게 아님.. 각 인덱스 자리 받아 출력....
//		int sum = 0; 
//		sum += arr[index1][0];
//		k = 0;
//		for (int i = 0; i < arr.length; i++) {
//			for (int j = 0; j < arr[i].length; j++) {
//				if (index2 == k+1) {
//					sum += arr[i][j];
//				}
//				k ++;
//			}
//		}
//		System.out.println(sum);
//		System.out.println(arr[index1][index2]);

// 문제2) 값을 입력받아 인덱스 2개 출력
// 예2) 값 입력 : 60
//		   인덱스1 출력 : 1	인덱스2 출력 : 2
int value = 100;
int id1 = -1, id2 = -1;
for (int i = 0; i < arr.length; i++) {
	for (int j = 0; j < arr[i].length; j++) {
		if (value == arr[i][j]) {
			id1 = i;
			id2 = j;
		}
	}
}
System.out.println(id1 + " / " + id2); 

// 문제3) 가장 큰 값의 인덱스 2개 출력
// 정답3) 2 2
int max = 0;
int index1 = 0, index2 = 0;
for (int i = 0; i < arr.length; i++) {
	for (int j = 0; j < arr[i].length; j++) {
		if(max < arr[i][j]) {
			index1 = i;
			index2 = j;
		}
	}
}
if (id1 == -1 && id2 == -1) {
	System.out.println("해당값 없음");
} else {
	System.out.printf("%d / %d \n",index1 , index2);
}
// 문제4) 값 2개를 입력받아 값 교체
value = 60;
for (int i = 0; i < arr.length; i++) {
	for (int j = 0; j < arr[i].length; j++) {
		if (value == arr[i][j]) {
			arr[i][j] = 100;
		}
	}
}
for (int i = 0; i < arr.length; i++) {
	System.out.println(Arrays.toString(arr[i]));
}

주석 부분 또 다시 이해를 잘못했다.
숫자 두개를 입력받아 arr[index1][index2]에 넣으면 간단하게 해결되는 문제인데 두 수를 합친 후 해당번째 수를 출력하느라 요상하게 풀었다.
어쩐지 기본문제인데 단계를 뛰었더라...

3. 이차원 배열 기본 문제3 - 가로세로 합구하기

import java.util.Arrays;

int[][] arr = {
		{101, 102, 103, 104},
		{201, 202, 203, 204},
		{301, 302, 303, 304}
	}; 
	
int[] garo = new int[3];
int[] sero = new int[4];
// 문제 1) 가로 합 출력
// 정답 1) 410, 810, 1210
	
// 문제 2) 세로 합 출력
// 정답 2) 603, 606, 609, 612

for (int i = 0; i < arr.length; i++) {
	int index = 0;
	for (int j = 0; j < arr[i].length; j++) {
		garo[i] += arr[i][j];
		sero[j] +=arr[i][index];
		index++;
	}
}
System.out.println(Arrays.toString(garo));
System.out.println(Arrays.toString(sero));

일차원 배열에서 풀었던 문제의 이차원 배열ver

기본 문제들은 일차원 배열에서 열심히 해서 그런지 술술 풀려서 딱히..코멘트를 달게 없다...

4. 2차원 정렬

Random rnd = new Random();

int[][] darr = new int[3][3]; 
int size = darr.length * darr[0].length;
int[] arr = new int[size];

for (int i = 0; i < arr.length; i++) {
	int rNum = rnd.nextInt(100);
	arr[i] = rNum;
}
System.out.println(Arrays.toString(arr));
System.out.println();
int temp = 0;
for (int i = 1; i < size; i++) {
	for (int j = 0; j < i; j++) {
		temp = arr[i];
		if (arr[i] < arr[j]) {
			arr[i] = arr[j];
			arr[j] = temp;
		}
	}
	System.out.println(Arrays.toString(arr));
	System.out.println("======================");
}
int k = 0;
for (int i = 0; i < darr.length; i++) {
	for (int j = 0; j < darr[i].length; j++) {
		darr[i][j] = arr[k];
		k+=1;
	}
}
for (int i = 0; i < darr.length; i++) {
	for (int j = 0; j < darr[i].length; j++) {
		System.out.printf("[%3d] ", darr[i][j]);
	}
	System.out.println();
}

일차원 직렬정렬의 이차원.ver

5. 관리비 문제

문제 1) 각층별 관리비 합 출력
정답 1) 4400, 7100, 5400
문제 2) 호를 입력하면 관리비 출력
정답 2) 입력 : 202 관리비 출력 : 2000
문제 3) 관리비가 가장 많이 나온 집, 적게 나온 집 출력
정답 3) 가장 많이 나온 집(201), 가장 적게 나온 집(303)
문제 4) 호 2개를 입력하면 관리비 교체 (101 , 102) ==> (2100, 1000)
문제 5) 관리비 많이 나온순서대로 관리비와 호수 출력 (정렬)

Scanner sc = new Scanner(System.in);
int[][] apt = {
		{ 101, 102, 103 },	
		{ 201, 202, 203 },	
		{ 301, 302, 303 }	
	};
	
int[][] pay = {
		{ 1000, 2100, 1300 },	
		{ 4100, 2000, 1000 },	
		{ 3000, 1600,  800 }
	};
/*
for (int i = 0; i <apt.length; i++) {
	int sum = 0;
	for (int j = 0; j < apt[i].length; j++) {
		sum += pay[i][j];
	}
	System.out.printf( (i+1)+"층 관리비 합 : ");
	System.out.println(sum);
}

int index = -1;
System.out.print("관리비 검색 호 입력 : ");
int search = sc.nextInt();		
for (int i = 0; i < apt.length; i++) {
	for (int j = 0; j < apt[i].length; j++) {
		index++;
		if (search == apt[i][j]) {
			search = index;
			break;
		}
	}
}
System.out.println(search);
index = 0;
for (int i = 0; i < pay.length; i++) {
	for (int j = 0; j < pay[i].length; j++) {
		if (search == index) {
			System.out.println("관리비 : " + pay[i][j]);
		}
		index++;
	}
}

int index = -1;
int min = 10000, max = 0;
int minIndex = 0, maxIndex = 0;
for (int i = 0; i < pay.length; i++) {
	for (int j = 0; j < pay[i].length; j++) {
		index++;
		if (max < pay[i][j]) {
			max = pay[i][j];
			maxIndex = index;
		}
		if (min > pay[i][j]) {
			min = pay[i][j];
			minIndex = index;
		}
	}
}
index = -1;
for (int i = 0; i < apt.length; i++) {
	for (int j = 0; j < apt[i].length; j++) {
		index ++;
		if (maxIndex ==index) {
			max = apt[i][j];
		}
		if (minIndex == index) {
			min = apt[i][j];
		}
	}
}
System.out.println("가장 많이 나온 집 : " + max);
System.out.println("가장 적게 나온 집 : " + min);

System.out.print("관리비 교체 첫번째 호 입력 : ");
int chage1 = sc.nextInt();
System.out.print("관리비 교체 두번째 호 입력 : ");
int chage2 = sc.nextInt();

int index = -1;
int home1 = -1;
int home2 = -1;
int temp = 0;
for (int i = 0; i < apt.length; i++) {
	for (int j = 0; j < apt[i].length; j++) {
		index++;
		if (chage1 == apt[i][j]) {
			home1 = index;
		}
		if (chage2 == apt[i][j]) {
			home2 = index;
		}
	}
}
index = -1;
int tempIndex = 0;
if (home1 != -1 && home2 != -1  ) {
	for (int i = 0; i < pay.length; i++) {
		for (int j = 0; j <pay[i].length; j++) {
			index++;
			if (home1 == index) {
				home1 = pay[i][j];
			} 
			if (home2 == index) {
				home2 = pay[i][j];
			}
		}
	}
}
temp = home1;
home1 = home2;
home2 = temp;

System.out.println(home1);
System.out.println(home2);
 */
int size = apt.length * apt[0].length;
int[] sampleApt = new int[size];
int[] samplePay = new int[size];

int index = 0;

for (int i = 0; i < pay.length; i++) {
	for (int j = 0; j < pay[i].length; j++) {
		sampleApt[index] = apt[i][j];
		samplePay[index] = pay[i][j];
		index++;
	}
}

System.out.println(Arrays.toString(sampleApt));
System.out.println(Arrays.toString(samplePay));

int max = 0;
int tempPay = 0;
int tempApt = 0;
for (int i = 0; i < size; i++) { 
	for ( int j = 0; j < size; j++) {
		if (samplePay[i] > samplePay[j]) {
			tempPay = samplePay[i];
			samplePay[i] = samplePay[j];
			samplePay[j] = tempPay;
			tempApt = sampleApt[i];
			sampleApt[i] = sampleApt[j];
			sampleApt[j] = tempApt;
		}
	}
}
System.out.println();
System.out.println(Arrays.toString(samplePay));
System.out.println(Arrays.toString(sampleApt));
index = 0;
for (int i = 0; i < apt.length; i++) {
	for (int j = 0; j < apt[i].length; j++) {
		apt[i][j] = sampleApt[index];
		pay[i][j] = samplePay[index];
		index++;
	}
}
System.out.println();
for (int i = 0; i < apt.length; i++) {
	for (int j = 0; j < apt[i].length; j++) {
		System.out.printf("[%3d] ", apt[i][j]);
	}
	System.out.println();
}
System.out.println();
for (int i = 0; i < apt.length; i++) {
	for (int j = 0; j < apt[i].length; j++) {
		System.out.printf("[%4d] ", pay[i][j]);
	}
	System.out.println();
}

여러줄 주석 부분은 코드가 요구사항에 맞게 작동하는지 확인 후 주석처리하고 다음 문제 풀어서 되어있음.

6. 그래프 문제

scoreList[] = {31, 76, 54, 2, 100, 23};

위 데이터는 학생 6명의 점수이다.
위 데이터를 그래프로 표현해볼려고한다.
표시는 10의 자리숫자로 표현해서 개수만큼 * 로 출력할려고한다.
예)
31 ==> ***
76 ==> *******
54 ==> *****
2 ==>
100 ==> **********
23 ==> **

int scoreList[] = { 31, 76, 54, 2, 100, 23 };
for (int i = 0; i < scoreList.length; i++) {
	int ten = scoreList[i] / 10;
	System.out.printf("%3d ==> ", scoreList[i]);
	for (int j = 0; j < ten; j++) {
	System.out.print("*");
	}
	System.out.println();
}

두번째 for문을 십의 자리수만큼 돌려주면 되는 간단한 문제

7. 다음 소수 찾기

  1. 숫자를 한 개 입력받는다.
  2. 입력받은 숫자보다 큰 첫 번째 소수를 출력한다.

예) Enter Number ? 1000
1000보다 큰 첫번재 소수는 1009
예) Enter Number ? 500
500보다 큰 첫번째 소수는 503

Scanner sc = new Scanner(System.in);
System.out.print("Enter Number ? ");
int num = sc.nextInt();
System.out.printf("%d보다 큰 첫번째 소수 ", num);
while (true) {
	int count = 0;
	for (int i = 1; i <= num; i++) {
		if (num % i == 0) {
			count++;
		}
	}
	if (count == 2) {
		System.out.print(num);
		break;
	}
	num++;
}

소수는 1보다 큰 자연수 중 1과 자기 자신만을 약수로 가지는 수이므로 입력값을 늘리면서 num을 나누고 count가 2일때 반복문을 종료하면 된다.

8. 배열 두개 정렬

int[] arr1 = { 9, 10, 3, 2, 20, 19 };
int[] arr2 = { 15, 12, 1, 5, 7, 8 };
int[] temp = null;
int num = 0;

for (int i = 0; i < arr1.length; i++) {
	for (int j =i; j < arr1.length; j++) {
		if (arr1[i] > arr1[j]) {
			num = arr1[i];
			arr1[i] = arr1[j];
			arr1[j] = num;
		}
	}
}
for (int i = 0; i < arr2.length; i++) {
	for (int j = i; j < arr2.length; j++) {
		if (arr2[i] > arr2[j]) {
			num = arr2[i];
			arr2[i] = arr2[j];
			arr2[j] = num;
		}
	}
}
System.out.println(Arrays.toString(arr1));
System.out.println(Arrays.toString(arr2));

int size = arr1.length + arr2.length;
temp = new int[size];

System.out.println(Arrays.toString(temp));
System.out.println();
int arr1Index = 0;
int arr2Index = 0;
for (int i = 0; i < size; i++) {
	if (arr1Index == arr1.length) {
		temp[i] = arr2[arr2Index];
		arr2Index++;
	} else if (arr2Index == arr2.length) {
		temp[i] = arr1[arr1Index];
		arr1Index++;
	} else {
		if (arr1[arr1Index] < arr2[arr2Index]) {
			temp[i] = arr1[arr1Index];
			arr1Index++;
		} else if (arr1[arr1Index] > arr2[arr2Index]) {
			temp[i] = arr2[arr2Index];
			arr2Index++;
		}
	}
}
System.out.println(Arrays.toString(temp));

처음 할때는 arr1, arr2를 temp 배열에 순차적으로 넣고 temp 배열 안에서 정리했는데 위의 방법이 훨씬 효율적이다.
위의 방법은 병합정렬은 아니고 두 배열이 정렬되어있는 특수한 경우에만 사용 가능하다.

9. 별찍기

int count = 0;
	/*
 * 문제 1)
 * #
 * ##
 * ###
 */

for (int i = 0; i < 3; i++) {
	for (int j = 0; j <= i; j++ ) {
		System.out.print("*");
	}
	System.out.println();
}
System.out.println();
/*
 * 문제 2)
 * ###
 * ##
 * #
 */

for (int i = 0; i < 3; i++) {
	for (int j = i; j < 3; j++) {
		System.out.print("*");
	}
	System.out.println(); 
}
System.out.println(); 
/* 
 * 문제 3)
 * @##
 * @@#
 * @@@
 */
//		count = 1;
//		for (int i = 1; i <= 3; i++) {
//			for (int j = 1; j <= 3; j++) {
//				System.out.printf("%d ", count % 2 );
//				if (count == 2 || count == 3 || count == 6) {
//					System.out.printf("*");
//				}  else {
//					System.out.printf("@");
//				}
//				count ++;
count = 0;
for (int i = 0; i < 3; i++) {
	for (int j = 0; j <= i; j++) {
		System.out.printf("@");
//				count++;
//				System.out.printf("%d ", count);
	}
	for (int j = i; j < 2; j++) {
		System.out.printf("*");
//				count++;
//				System.out.printf("%d ", count);
	}
	System.out.println();
}
System.out.println();

/*
 * 문제 4)
 *   #
 *  ###
 * #####
 */
count = 0;
for (int i = 0; i < 3; i++) {
	for (int j = i+1; j <3; j++) {
		System.out.printf(" ");
	}
	for (int j = 0; j <= i; j++) {
		System.out.printf("|__|");
	}
	if (i > 0) {
		for (int j = 0; j <i; j++) {
			System.out.printf("*");
		}
	}
	System.out.println();
}
System.out.println();
/*
 * 문제 5)
 * #####
 *  ###
 *   #
 */
for(int i = 0; i < 3; i++) {
	if (i > 0) {
		for (int j = 0; j < i; j++) {
			System.out.printf(" ");
		}
	}
	for (int j = i; j < 3; j++) {
		System.out.printf("*");
	}
	if (i < 2) {
		for (int j =i; j < 2; j++) {
			System.out.printf("*");
		}
	}
	System.out.println();
}

나의 트라우마 나의 악몽 별찍기
... 선생님이 보고 신기하게 풀었구나 말하고 갔다...

지금봐도 강박관념에 잡혀있었구나 느껴지는 코드

다음날 다시 풀어본 코드는 아래와 같다

/*
 * 문제 1)
 * #
 * ##
 * ###
 */
for (int i = 0; i < 3; i++) {
	for (int j = 0; j <= i; j++) {
		System.out.printf("*");
	}
	System.out.println();
}
System.out.println("================");
/*
 * 문제 2)
 * ###
 * ##
 * #
 */
for (int i = 0; i < 3; i++) {
	for (int j = i; j < 3; j++ ) {
		System.out.printf("*");
	}
	System.out.println();
}
System.out.println("================");
/*
 * 문제 3)
 * @##
 * @@#
 * @@@
 */
for (int i = 0; i < 3; i++) {
	for (int j = 0; j <= i; j++) {
		System.out.printf("@");
	}
	for (int j =i+1; j <=2; j++) {
		System.out.printf("*");
	}
	System.out.println();
}
System.out.println("================");
/*
 * 문제 4)
 *   #
 *  ###
 * #####
 */
int temp = 0;
for (int i = 0; i < 3; i++) {
	for (int j = i; j < 2; j++) {
		System.out.printf("   ");
	}
	for (int j = 0; j <= temp; j++) {
		System.out.printf("|__|");
	}
	System.out.println();
	temp += 2;
}
System.out.println("================");

/*
 * 문제 5)
 * #####
 *  ###
 *   #
 */
temp = 5;
for (int i = 0; i < 3; i++) {
	for (int j = 0; j <= i-1; j++) {
		System.out.printf(" ");
	}
	for (int j = 0; j < temp; j++) {
		System.out.printf("*");
	}
	temp-=2;
	System.out.println();
}

전날에 스스로 해내서 트라우마가 극복됐는지 훨씬 보기 좋은 코드가 나왔다.
이와 더불어 농담으로 선생님께 제가 해냈습니다. 극복했습니다 말하며 별찍기 1번 문제에 대한 풀이 코드로 아래의 코드를 보여드렸다.

System.out.printf("*");
System.out.printf("**");
System.out.printf("***");

반복도 안돌고 이게 제일 빠른거 같습니다 했더니 웃으셨다. 웃으시면서 과거 기수 선배님중에 기술면접때 저렇게 찍고 합격하신 선배님이 계신다고 말씀해주셨다.
존경합니다. 선배님

10. 소수 여러개 찾기

[소수여러개찾기]
정수 한 개를 입력받아, 2부터 해당 숫자까지의 모든 소수 출력
예)
입력 : 20
2, 3, 5, 7, 11, 13, 17, 19

Scanner sc = new Scanner(System.in);
System.out.print("정수 입력 : ");
int num = sc.nextInt();
// 소수 = 1과 자기 자신만을 약수로 가지는 수 ==> 나눴을때 나머지 0 이 2개가 되는 수
for (int i = 2; i <=num; i++) {
	int count = 0;
	for (int j = 1; j <= num; j++) {
		if (i % j == 0) {
			count++;
		}
	}
	if (count == 2) {
		System.out.printf("%d ",i);
	}
}

매 숫자마다 나눠지는 숫자로 소수 판별을 한다. 그런데 매 숫자마다 판별을 해봤다면 에라토스테네스의 체로 판별해보라고 제시되어 있었다. ...네?

Scanner sc = new Scanner(System.in);
System.out.print("정수 입력 : ");
int num = sc.nextInt();
// 배열에 원소 삽입

int[] array = new int[num + 1];
for (int i = 2; i <= num; i++) {
    array[i] = i;
}
for (int i = 2; i <= num; i++) {
    // i번째 배열값이 0이면 건너뜀
    if (array[i] == 0) {
        continue;
    }
    // i의 배수인 원소들을 모두 지워줌 
    for (int j = i * i; j <= num; j += i) {
        array[j] = 0;
    }
    System.out.println();
}
// 0이 아닌(지워지지 않은) 숫자들만 출력 
for (int i = 0; i < array.length; i++) {
    if (array[i] != 0) {
        System.out.print(array[i] + " ");
        }
    }
}

뭔가 한끝이 부족해서 반나절동안 붙잡고 있다가 구글로 검색한 덕분에 해결했다.
배수는 소수가 될 수 없으므로 배열 안의 배수값들을 0으로 바꾼 후 0이 아닌 수만 출력했다.

11. 시험지 나눠주기 문제

[시험지나눠주기]

아래 2차원배열은 3학년1반의 학생수를 표현한다.
세로 4 가로 5의 총 학생수는 20명이고,
각각의 값들은 각학생별 시험을보기위한 필요한 페이지 수이다.
학생마다 필요한 페이지수가 다르다.
시험지를 나눠줄려고 한다. 인덱스위치 (0,0) 부터 나눠줄려고하는데

나눠주기 편하게하기위해서 지그재그로 나눠줄려고 한다.
첫번째줄은 앞에서 부터 뒤로 이동한다. 3,1,5,4,1
두번째줄은 뒤에서 부터 앞으로 이동한다. 8,2,4,6,1
다시 세번째줄은 앞에서부터 뒤로이동한다. 2,3,5,5,2
다시 네번째줄은 뒤에서부터 앞으로 이동한다. 2,1,7,1,6

랜덤으로 학생수 1~20을 저장하고 , 각학생별 필요한 페이지수의 합을 출력한다.
예) 7 ==> {3 + 1 + 5 + 4 + 1} + {8 + 2}
예) 12 ==> {3 + 1 + 5 + 4 + 1} + {8 + 2 + 4 + 6 + 1} + {2 + 3}

Random rnd = new Random();
int rNum = rnd.nextInt(20)+1 ;
System.out.println("랜덤 학생 수 : " + rNum);
int darr[][] = {
	{3,1,5,4,1},
	{1,6,4,2,8},
	{2,3,5,5,2},
	{6,1,7,1,2},
};
int widthIndex = 0;
int heightIndex = 0;

int sum = 0;
boolean stop = false;
for (int i = 0; i < darr.length; i++) {
	if (stop == true) {
		System.out.print(sum);
		break;
	}
	if (widthIndex == 0) {
		for (int j = 0; j < darr[i].length; j++) {
			if (rNum == 0) {
				stop = true;
				break;
			}
			System.out.print(darr[heightIndex][widthIndex] + " ");
			sum += darr[heightIndex][widthIndex];
			widthIndex++;
			rNum--;
		}
		heightIndex++;
	} else if (widthIndex == 5) {
		for (int j = 0; j < darr[i].length; j++) {
			if (rNum == 0) {
				stop = true;
				break;
			}
			widthIndex--;
			System.out.print(darr[heightIndex][widthIndex] + " ");
			sum += darr[heightIndex][widthIndex];
			rNum--;
		}
		heightIndex++;
	}
	System.out.println();
}

특정 값에 도달했을때 row에 관한 인덱스를 변경해주면 되는 문제, 왜 풀때 row와 column이 생각 안났을까...

12. 압축 풀기 문제

array[][] = {3,2},{5,6},{2,1},{4,3}
위 데이터는 압축한 데이터이다.
위데이터의 규칙은 2개씩 짝을 이룬다.
1) 앞의 숫자 ==> 데이터
2) 뒤의 숫자 ==> 개수이다.
예) {3,2} ==> 33
예) {5,6} ==> 555555
예) {2,1} ==> 2
예) {4,3} ==> 444
실제 데이터는 335555552444 인것이다.
문제) 위데이터사이즈만큼 배열을 만들고 각각의 값을 저장후 출력
예) temp = {3,3,5,5,5,5,5,5,2,4,4,4}

int array[][] = {
		{3,2},{5,6},{2,1},{4,3}
	};
int [] temp;
int size = 0;
int index = 1;
for (int i = 0; i < array.length; i++) {
	size += array[i][index];
}
System.out.println(size);
System.out.println();
temp = new int[size];
index = 0;
int count = 0;
for (int i = 0; i < size; i++) {
	temp[i] = array[index][0];
	count++;
	if (count == array[index][1]) {
		index++;
		count = 0;
	}
}
System.out.println(Arrays.toString(temp));

지금보니 size.length + size[0].length를 구했으면 됐었는데 당시에는 기묘하게 구했다.
array[index][1]이 반복횟수이므로 count변수가 이를 도달할때마다 index를 증가시키는 식으로 해결했다.

13. 압축하기

int 압축전[] = { 3, 3, 5, 5, 5, 5, 5, 3, 4, 4, 4 };
int 압축후[][] = new int[4][2];
위 데이터는 압축전 데이터이다.
연속으로 이뤄진 데이터를 모아 압축할려고한다.
예) 33 ==> {3,2}
예) 55555 ==> {5,5}
예) 3 ==> {3,1};
예) 444 ==> {4,3};
0번은 압축할값 , 1번은 연속된개수
문제) 위 압축전데이터를 분석후 2차원으로 저장하시요.

int 압축전[] = { 3, 3, 5, 5, 5, 5, 5, 3, 4, 4, 4 };
int 압축후[][] = new int[4][2];

int temp = 압축전[0];
int rowIndex = -1;
int count = 1;
// 다른 숫자를 만나면 다음 행 인덱스
for (int i = 1; i < 압축전.length; i++) {
	if (temp != 압축전[i]) {
		rowIndex++;
		압축후[rowIndex][0] = temp;
		압축후[rowIndex][1] = count;
		temp = 압축전[i];
		count = 0;
	}
	count++;
	if (i == 압축전.length-1) {
		rowIndex++;
		압축후[rowIndex][0] = temp;
		압축후[rowIndex][1] = count;
	}
}
for (int i = 0; i < 압축후.length; i++) {
	System.out.println(Arrays.toString(압축후[i]));
}

12번째 문제와 반대되는 문제, 마지막 4의 경우에서 원하는 답이 안나왔었다. 그래서 해당 수에 도달하면 값을 구하는 조건식을 지정하여 해결했다.

14. 구구단 옆으로 출력

아래와같이 구구단을 옆으로 출력해보세요.

 
 2*1 = 2	3*1 = 3  .....  	9*1 = 9
 2*2 = 4  	3*2 = 6	 .....		9*2 = 18
 2*3 = 6  	3*3 = 9	 .....		9*3 = 27
 ...      	...					...
 ...      	...					...
 2*9 = 18	3*9 = 27 .....		9*9 = 81
for (int i = 1; i <= 9; i++) {
	for (int j = 2; j <= 9; j++) {
		System.out.printf("%d *%2d = %2d  ", j, i, j * i);
	}
	System.out.println();
}

어느쪽이 기준점으로 출력을 하는지만 알고 있으면 간단히 풀리는 문제

0개의 댓글