๋ถ๋ถ์งํฉ ๊ตฌํ๊ธฐ
๊ธฐ๋ณธ ๋ฌธ์
ํ์ด ์ฝ๋
import java.util.Arrays;
public class PartElements {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, -1, -5};
// ๋ชจ๋ ๋ถ๋ถ์งํฉ์ ๊ฒฝ์ฐ์ ์
for (int i = 1; i < (1 << array.length); i++) {
int[] temp = new int[array.length]; // ์์ ๋ถ๋ถ ์งํฉ
int count = 0; // ์๋ก์ด ๋ฐฐ์ด ํฌ๊ธฐ
boolean isOdd = true; // ํ์ ์ฌ๋ถ ํ์ธ
// ๋ถ๋ถ์งํฉ ์์ฑ
for (int j = 0; j < array.length; j++) {
if ((i & (1 << j)) != 0) {
if (array[j] % 2 == 0) {
isOdd = false;
}else{
temp[count++] = array[j];
}
}
}
// ์ถ๋ ฅ
if (isOdd) System.out.println(Arrays.toString(Arrays.copyOf(temp,count)));
}
}
}
์ค๋ช
for (int i = 1; i < (1 << array.length); i++) {
int[] temp = new int[array.length]; // ์์ ๋ถ๋ถ ์งํฉ
int count = 0; // ์๋ก์ด ๋ฐฐ์ด ํฌ๊ธฐ
boolean isOdd = true; // ํ์ ์ฌ๋ถ ํ์ธ
for (int j = 0; j < array.length; j++) {
if ((i & (1 << j)) != 0) {
if (array[j] % 2 == 0) {
isOdd = false;
}else{
temp[count++] = array[j];
}
}
}
i | i์ ๋นํธ๊ฐ | j | (1 << j) | i & (1 << j) | i & (1 << j)์ ๊ฐ |
1 | 000001 | 0 | 000001 | 000001 | 1 |
1 | 000001 | 1 | 000010 | 000000 | 0 |
1 | 000001 | 2 | 000100 | 000000 | 0 |
1 | 000001 | 3 | 001000 | 000000 | 0 |
1 | 000001 | 4 | 010000 | 000000 | 0 |
1 | 000001 | 5 | 100000 | 000000 | 0 |
2 | 000010 | 0 | 000001 | 000000 | 0 |
2 | 000010 | 1 | 000010 | 000010 | 2 |
2 | 000010 | 2 | 000100 | 000000 | 0 |
2 | 000010 | 3 | 001000 | 000000 | 0 |
2 | 000010 | 4 | 010000 | 000000 | 0 |
2 | 000010 | 5 | 100000 | 000000 | 0 |
... | |||||
63 | 111111 | 0 | 000001 | 000001 | 1 |
63 | 111111 | 1 | 000010 | 000010 | 2 |
63 | 111111 | 2 | 000100 | 000100 | 4 |
63 | 111111 | 3 | 001000 | 001000 | 8 |
63 | 111111 | 4 | 010000 | 010000 | 16 |
63 | 111111 | 5 | 100000 | 100000 | 32 |
์ ํ์ ๊ฐ์ด i & (1 << j) ๊ฐ์ด 0์ด ์๋๋ if๋ฌธ ์์ผ๋ก ๋ค์ด๊ฐ๊ฒ๋ ํ๋ค. ์ฆ, 1~63๊น์ง ์ด์ง์๋ก ๋ํ๋ด๋ฉด ๋ชจ๋ ๋ถ๋ถ์งํฉ์ ๊ฒฝ์ฐ์ ์๋ฅผ ๊ตฌํ ์ ์๋ค. ๋๋จธ์ง ํ์๋ง ๊ฑธ๋ฌ์ฃผ๋ ๋ก์ง์ ํด๋น if๋ฌธ์์ ์ถ๊ฐ์ ์ผ๋ก ๋ฃ์ด์ฃผ๋ฉด ๋๋ค.
22
if (isOdd) System.out.println(Arrays.toString(Arrays.copyOf(temp,count)));
๊ธฐ์กด์ temp๋ผ๋ ๋ฐฐ์ด์ array๋ฐฐ์ด์ ํฌ๊ธฐ ๊ทธ๋๋ก ์์ฑํด์ฃผ์๋ค. ํ์๋ง ๋ฐ๋ก ๋ฝ์๋๊ธฐ ๋๋ฌธ์ ๋๋จธ์ง ์๋ฆฌ์๋ 0์ด ์ฑ์์ก์ ๊ฒ์ด๋ค. 0์ ๋ชจ๋ ์ญ์ ํด์ฃผ๊ธฐ ์ํด ๋ฝ์๋ธ ๋ฐฐ์ด์ ํฌ๊ธฐ ๋งํผ๋ง ๋ฐฐ์ด ๋ณต์ฌ๋ฅผ ํด์ฃผ์๋ค.
๊ฒฐ๊ณผ

๋นํธ์ฐ์ฐ์ผ๋ก ์ ๊ทผํ์ฌ ๋ถ๋ถ์งํฉ์ ๊ตฌํ๋ ๋ฌธ์ ๋ฅผ ํ๋ ๋ ํ์ด๋ณด์.
๋ณํ ๋ฌธ์ : ํฉ๊ธ๋ก๋ณถ์ด๊ฐ ๋จน๊ณ ์ถ์ด์
ํ์ด ์ฝ๋
import java.util.Arrays;
public class Gold {
public static void main(String[] args) {
String[] names = {"์๋ชฝ", "๋ฐ๋๋", "์ ํ๋ง๊ณ ", "๋ฉ๋ก ", "์ค๋ ์ง", "์ฒด๋ฆฌ", "์คํธ๋ก๋ฒ ๋ฆฌ", "ํค์", "๋ฆฌ์น"};
int[] array = {15000, 2000, 10000, 7000, 15000, 1000, 2000, 4000, 5000};
for (int i = 1; i < (1 << array.length); i++) {
String[] temp = new String[array.length];
int count = 0;
int sum = 0;
for (int j = 0; j < array.length; j++) {
if ((i & (1 << j)) != 0) {
sum += array[j];
temp[count++] = names[j];
}
}
String[] resultArr = Arrays.copyOf(temp, count);
if (sum >= 30000 && resultArr.length <=3) System.out.println(Arrays.toString(resultArr));
}
}
}
๊ฒฐ๊ณผ
๋๊ธ