버블 정렬
- 앞에서부터 현재 값과 바로 다음 (오른쪽) 의 값을 비교한다.
- 현재 값이 다음 값보다 크면 값을 교환한다.
- 다음 값으로 이동하여 해당 값과 그 다음 값을 비교한다.
Q. 버블 정렬 구현 해보기
package array;
public class Test16 {
public static void main(String[] args) {
// 버블 정렬 (Bubble Sort)
// 입력
int[] data = new int[] { 30, 50, 20, 10, 40, 7, 5, 80, 25 };
// 출력
System.out.print("[");
for (int i = 0; i < data.length; i++) {
System.out.print(data[i]);
if (i < data.length - 1) {// 마지막 데이터가 아니라면
System.out.print(" , ");
}
}
System.out.print("]");
System.out.println();
// 처리 : 버블정렬
for (int h = data.length - 1; h > 0; h--) {
for (int k = 0; k < h; k++) {
if (data[k] > data[k + 1]) {
int temp = data[k];
data[k] = data[k + 1];
data[k + 1] = temp;
}
}
}
// 출력
System.out.print("[");
for (int i = 0; i < data.length; i++) {
System.out.print(data[i]);
if (i < data.length - 1) {// 마지막 데이터가 아니라면
System.out.print(" , ");
}
}
System.out.print("]");
System.out.println();
}
}
- 정답
[30 , 50 , 20 , 10 , 40 , 7 , 5 , 80 , 25]
[5 , 7 , 10 , 20 , 25 , 30 , 40 , 50 , 80]
삽입 정렬
- 좌측부터 순서대로 백업 후 들어갈 위치를 만든 뒤 삽입하는 방식의 정렬
Q. 삽입 정렬 구현 해보기
package array;
public class Test17 {
public static void main(String[] args) {
// 삽입 정렬 (Insertion Sort)
// 좌측부터 순서대로 백업 후 들어갈 위치를 만든 뒤 삽입하는 방식의 정렬
//입력
int[] data = new int[] {30, 50, 20, 10, 40, 25, 35, 15, 5, 45, 90};
//출력
System.out.print("[");
for(int i=0; i < data.length; i++) {
System.out.print(data[i]);
if(i < data.length - 1) {//마지막 데이터가 아니라면
System.out.print(" , ");
}
}
System.out.print("]");
System.out.println();
//처리 : 삽입정렬
//for(int k=0; k < 5; k++) {
for(int k=0; k < data.length; k++) {
int backup = data[k];//백업 데이터
int location = k;//삽입 위치
for(int i=k-1; i >= 0; i--) {
if(backup < data[i]) {//backup보다 data[i]가 더 크다면
data[i+1] = data[i];//데이터(data[i])를 우측으로 1칸 이동
location--;//위치(location) 1 감소
}
}
data[location] = backup;//백업 데이터를 목적지(location) 위치에 삽입
}
//출력
System.out.print("[");
for(int i=0; i < data.length; i++) {
System.out.print(data[i]);
if(i < data.length - 1) {//마지막 데이터가 아니라면
System.out.print(" , ");
}
}
System.out.print("]");
System.out.println();
}
}
- 정답
[30 , 50 , 20 , 10 , 40 , 25 , 35 , 15 , 5 , 45 , 90]
[5 , 10 , 15 , 20 , 25 , 30 , 35 , 40 , 45 , 50 , 90]
Random(랜덤)
무작위 데이터
다음에 뭐가 나올지 예측할 수 없는 데이터
로또, 주사위
프로그래밍에서 확률적인 처리가 가능하도록 만들어주는 기술
프로그래밍에서는 랜덤한 "정수"를 추첨하여 사용하는 경우가 많다
추첨 방법
Math.random() 명령을 사용하는 방법
0 이상 1 미만의 double 데이터를 무작위로 추첨하는 명령
0.xxxxx 가 나오는 명령
Random 이라는 도구를 사용하는 방법
ex. 랜덤값을 뽑는 공식을 해보면서 1부터 45사이의 정수를 추첨을 구현 해보기
package random;
import java.util.Random;
public class Test01 {
public static void main(String[] args) {
double a = Math.random(); // 0 이상 1미만 double
double b = a * 10; // 0 이상 10미만 double
int c = (int) b; // 0 이상 10 미만 int
int d = c + 1; // 0 이상 11 미만 int (원하는 범위)
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
// Math.random()을 이용하여 랜덤값을 뽑는 공식
// int number =(int)(Math.random()*개수) + 시작;
// = Java는 1부터 10까지라고 표현하지 않고 1부터 10개라고 표현한다.
// = 만약 10부터 99까지라면 Java는 10부터 90개라고 현한다.
int number = (int) (Math.random() * 45) + 1; //같은 표현
System.out.println("number = " + number);
// Random을 이용해서 랜덤값을 뽑는 방법
Random r = new Random();
int number2 = r.nextInt(45) + 1; //같은표현
System.out.println("number2 = " + number2);
}
}
Q. 다음 요구사항에 맞느 랜덤값을 추첨하여 화면에 출력
1. 주사위 1개를 던진 예상 결과
2. 로또번호 1개를 추첨한 결과
3. 랜덤한 6자리 정수(OTP 번호)
package random;
import java.util.Random;
public class Test02 {
public static void main(String[] args) {
// 1. 주사위 1개를 던진 예상 결과
Random d = new Random();
int dice = d.nextInt(6) + 1;
System.out.println("주사위 1개를 던진 결과 = " + dice);
// 2. 주사위 1개를 던진 예상 결과
int lotto = d.nextInt(45) + 1;
System.out.println("로또번호 1개를 추첨한 결과 = " + lotto);
// 3. 랜덤한 6자리 정수(OTP 번호)
// 범위 100000부터 999999까지 -> 100000부터 900000까지
int otp = d.nextInt(900000) + 100000;
System.out.println("랜덤한 6자리 정수 = " + otp);
}
}
- 정답
주사위 1개를 던진 결과 = 6
로또번호 1개를 추첨한 결과 = 21
랜덤한 6자리 정수 = 694154
Q. 사용자에게 랜덤으로 구구단 1문제를 출제하여 정답을 입력받고 맞았는지 틀렸는지 판정하여 출력
2 X 3 = 6 정답입니다
5 X 7 = 32 오답입니다
package random;
import java.util.Random;
import java.util.Scanner;
public class Test03 {
public static void main(String[] args) {
Random r = new Random();
int number = r.nextInt(8) + 2;
int number2 = r.nextInt(9) + 1;
System.out.print(number + " X " + number2 + " = ");
Scanner sc = new Scanner(System.in);
int answer = sc.nextInt();
sc.close();
if (number * number2 == answer) {
System.out.println("정답입니다.");
} else {
System.out.println("오답입니다.");
}
}
}
- 정답
9 X 5 = 45
정답입니다.
Q. 우리 게임에서는 이용자를 위해 랜덤박스 이벤트를 진행합니다.
확률 공개 규정에 의해 공개된 확률은 다음과 같습니다
- 최상급 아이템 : 1%
- 상급 아이템 : 5%
- 중급 아이템 : 14%
- 일반 아이템 : 80%
프로그램을 실행하면 위의 확률에 맞게 랜덤으로 하나의 랜덤박스 추첨 결과를 출력
package random;
import java.util.Random;
public class Test04 {
public static void main(String[] args) {
Random r = new Random();
int box = r.nextInt(100) + 1;
if (1 == box) {
System.out.println("최상급 아이템");
} else if (box <= 6) {
System.out.println("상급 아이템");
} else if (box <= 20) {
System.out.println("중급 아이템");
} else {
System.out.println("일반 아이템 ");
}
}
}
- 정답
확률
Q . 다음 요구사항에 맞게 프로그래밍 코드를 구현하세요.
1. 주사위를 10번 던진 결과를 배열에 저장하세요.
2. 결과를 출력하세요.
3. 주사위 평균을 구하여 출력하세요
4. 결과를 내림차순으로 정렬하여 출력하세요(정렬방법 무관)
5. 각 주사위값이 나온 횟수를 구하여 출력하세요.
package random;
import java.util.Random;
public class Test05 {
public static void main(String[] args) {
//배열을 이용해서 데이터를 저장~
Random r = new Random();
int[] dice = new int[10];
for(int i=0; i < dice.length; i++) {
dice[i] = r.nextInt(6) + 1;//1부터 6개
}
//출력
for(int i=0; i < dice.length; i++) {
System.out.println("주사위 : "+dice[i]);
}
//평균 = 합계 / 개수 = 합계 / data.length
int total = 0;
for(int i=0; i < dice.length; i++) {
total += dice[i];
}
float average = (float)total / dice.length;
System.out.println("평균 주사위 : "+average);
//처리 : 삽입정렬
for(int k=0; k < dice.length; k++) {
int backup = dice[k];//백업 데이터
int location = k;//삽입 위치
for(int i=k-1; i >= 0; i--) {
if(backup > dice[i]) {//backup보다 data[i]가 더 크다면
dice[i+1] = dice[i];//데이터(data[i])를 우측으로 1칸 이동
location--;//위치(location) 1 감소
}
}
dice[location] = backup;//백업 데이터를 목적지(location) 위치에 삽입
}
//출력
for(int i=0; i < dice.length; i++) {
System.out.println("주사위 : "+dice[i]);
}
//주사위 값별 빈도(카운트) 측정
// -> 주사위 값이 6종류니까 카운트 변수도 6개가 필요 -> 카운트 배열 1개로 처리 가능
//int count1 = 0, count2 = 0, count3 = 0, count4 = 0, count5 = 0, count6 = 0;
int[] count = new int[6];//(count) -----> [ 0 ] [ 0 ] [ 0 ] [ 0 ] [ 0 ] [ 0 ]
for(int i=0; i < dice.length; i++) {
int d = dice[i];
count[d-1]++;
}
for(int i=0; i < count.length; i++) {
System.out.println((i+1) + " 나온 횟수 : "+count[i]);
}
}
}
- 정답
주사위 : 6
주사위 : 5
주사위 : 1
주사위 : 4
주사위 : 2
주사위 : 6
주사위 : 5
주사위 : 3
주사위 : 3
주사위 : 6
평균 주사위 : 4.1
주사위 : 6
주사위 : 6
주사위 : 6
주사위 : 5
주사위 : 5
주사위 : 4
주사위 : 3
주사위 : 3
주사위 : 2
주사위 : 1
1 나온 횟수 : 1
2 나온 횟수 : 1
3 나온 횟수 : 2
4 나온 횟수 : 1
5 나온 횟수 : 2
6 나온 횟수 : 3
'Java 웹 개발' 카테고리의 다른 글
21.08.30 - 웹 개발 입문 14일차 (0) | 2021.08.30 |
---|---|
21.08.27 - 웹 개발 입문 13일차 (0) | 2021.08.29 |
21.08.25 - 웹 개발 입문 11일차 (0) | 2021.08.25 |
21.08.24 - 웹 개발 입문 10일차 (0) | 2021.08.24 |
21.08.23 - 웹 개발 입문 9일차 (0) | 2021.08.23 |