카이 호스트만의 코어 자바8 1장 연습문제 일부 코드

연습문제 답

일부 중요하거나 풀어보고 싶은 문제만 풀었으며, 그에 대한 나의 코드를 공개한다.

6번 문제

재귀(Recursion) 방식과 동적 계획법(Dynamic Programing) 방식으로 풀었다.
한 가지 방법으로 풀어도 되지만, 둘 다 공부 할 겸 두 방식 모두 풀었다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import java.math.BigInteger;

/**
* Created by sanghyoun on 2017. 3. 14..
*/
public class Ch1_6 {
public static BigInteger[] dp = new BigInteger[1000];

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// 0 이 입력 될 때까지 입력 무한 반복.
while (true) {
System.out.print("Tpye number (max num = 1000) : ");
int max = Integer.parseInt(input.nextLine());
if (max == 0) {
System.out.println("End of Factorial.");
break;
}
// 결과값 출력
System.out.println(factorialDP(max));
}
}

// 일반적인 Recursive factorial 계산
public static BigInteger factorial(int num) {
if (num == 1) {
return new BigInteger("1");
} else {
return factorial(num - 1).multiply(new BigInteger(Integer.toString(num)));
}
}

// Dynamic Programing 방식 factorial 계산
public static BigInteger factorialDP(int num) {
if (num == 1) {
Ch1_6.dp[num] = new BigInteger("1");
} else if (Ch1_6.dp[num] == null) {
Ch1_6.dp[num] = Ch1_6.factorialDP(num - 1).multiply(new BigInteger(Integer.toString(num)));
}
return Ch1_6.dp[num];
}
}

13번 문제

문제의 해석이 이상하게 된 것인지 제대로 이해가 가지 않았다.
일단 내가 이해 한 바는 아래와 같다.

1~49로 채워진 배열 리스트에서 임의의 인덱스에 있는 숫자를 뺀다.
6번 반복 후, 없어진 수를 찾아 출력한다.

이렇게 이해 하고 문제를 풀었다.
디버깅 용으로 출력도 만듬

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import java.util.ArrayList;
import java.util.Random;

/**
* Created by sanghyoun on 2017. 3. 14..
*/
public class Ch1_13 {
public static void main(String[] args) {
ArrayList<Integer> nums = new ArrayList<>();
for(int i=0; i<49; i++) {
nums.add(i+1);
}
Random generator = new Random();
System.out.print("Removed [ ");
for(int i=0; i<6; i++) {
int num = generator.nextInt(48-i);
System.out.print(nums.get(num) + " ");
nums.remove(num);
}
System.out.println("]");
int count=1;
System.out.print("Result [ ");
for(int i=0; i<43; i++) {
if(nums.get(i) == count) {
count++;
} else {
System.out.print(count + " ");
count += 2;
}
}
System.out.println("]");
}
}

14번 문제

역시 문제가 이상 한 것 같다. MagicSquare 라는데 마방진 이다.
마방진은 가로, 세로, 대각선 각각의 합이 모두 같아야 하는데, 주어진 예제에서는 대각선이 일치하지 않았다.
그래서 구글링을 통해 다른 예제를 가져왔다.

120 103 86 69 52 35 18 1 224 207 190 173 156 139 122
121 119 102 85 68 51 34 17 15 223 206 189 172 155 138
137 135 118 101 84 67 50 33 16 14 222 205 188 171 154
153 136 134 117 100 83 66 49 32 30 13 221 204 187 170
169 152 150 133 116 99 82 65 48 31 29 12 220 203 186
185 168 151 149 132 115 98 81 64 47 45 28 11 219 202
201 184 167 165 148 131 114 97 80 63 46 44 27 10 218
217 200 183 166 164 147 130 113 96 79 62 60 43 26 9
8 216 199 182 180 163 146 129 112 95 78 61 59 42 25
24 7 215 198 181 179 162 145 128 111 94 77 75 58 41
40 23 6 214 197 195 178 161 144 127 110 93 76 74 57
56 39 22 5 213 196 194 177 160 143 126 109 92 90 73
72 55 38 21 4 212 210 193 176 159 142 125 108 91 89
88 71 54 37 20 3 211 209 192 175 158 141 124 107 105
104 87 70 53 36 19 2 225 208 191 174 157 140 123 106

당연히 이 예제의 값은 Yes가 나옴.
또다른 예제

11 18 25 2 9
10 12 19 21 3
4 6 13 20 22
23 5 7 14 16
17 24 1 8 15

2차원 ArrayList를 사용했다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import java.util.ArrayList;
import java.util.Scanner;

/**
* Created by sanghyoun on 2017. 3. 15..
*/
public class Ch1_14 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<ArrayList<Integer>> dim2num = new ArrayList<>();
while (scan.hasNextLine()) {
String line = scan.nextLine();
if ("".equals(line)) {
break;
}
String[] nums = line.split(" ");
ArrayList<Integer> temp = new ArrayList<>();
for (String num : nums) {
temp.add(Integer.parseInt(num));
}
dim2num.add(temp);
}
if (magicSquare(dim2num)) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}

public static boolean magicSquare(ArrayList<ArrayList<Integer>> arr) {
int sum=0;
// 동남쪽 대각선 합 구하기
for (int i=0; i < arr.size(); i++) {
sum += arr.get(i).get(i);
}

// 동북쪽 대각선 검사
int temp=0;
for (int i=arr.size() - 1; i >= 0; i--) {
temp += arr.get(i).get(i);
}
if (sum != temp) {
return false;
}
// 가로 검사
for (ArrayList<Integer> yPos : arr) {
temp = 0;
for (int i=0; i<yPos.size(); i++) {
temp += yPos.get(i);
}
if (sum != temp) {
return false;
}
}
// 세로 검사
for (int i=0; i < arr.size(); i++) {
temp = 0;
for (ArrayList<Integer> xPos : arr) {
temp += xPos.get(i);
}
if (sum != temp) {
return false;
}
}
return true;
}
}

15번 문제

파스칼 삼각형 이다.
문제에서는 2차원 ArrayList 에 작성 n의 파스칼 삼각형을 작성하라고 나와있어서
따로 입력을 받고 해당 숫자만큼 반복하게 만들었다.
확인을 위한 출력 코드까지 포함하고 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import java.util.ArrayList;
import java.util.Scanner;

/**
* Created by sanghyoun on 2017. 3. 20..
*/
public class Ch1_15 {
public static void main(String[] args) {
System.out.print("Type number : ");
Scanner input = new Scanner(System.in);
int num = Integer.parseInt(input.nextLine());
ArrayList<ArrayList<Integer>> tri = new ArrayList<>();
pascal(num, tri);
for(ArrayList<Integer> first : tri) {
System.out.print("[ ");
for(int tmp : first) {
System.out.print(tmp + " ");
}
System.out.println("]");
}
}

public static void pascal(int num, ArrayList<ArrayList<Integer>> tri) {
for (int i = 0; i < num; i++) {
ArrayList<Integer> temp = new ArrayList<>();
// 가장 앞에 있는 1을 추가함
temp.add(1);
// 각 n번째의 숫자를 위의 배열에서 읽어온 다음 더해서 저장.
for (int k = 1; k < i; k++) {
int sum = tri.get(i-1).get(k - 1) + tri.get(i-1).get(k);
temp.add(sum);
}
// 가장 뒤에 있는 1을 추가함
if (i != 0) {
temp.add(1);
}
tri.add(temp);
}
}
}

댓글