프로그래밍/JAVA 자바
배열, 2차원 배열, 여러가지 정렬 방법
Heidong
2021. 7. 13. 01:33
반응형
년도 입력받아 입력 받은 년도의 띠를 구해라
package ex0712;
import java.util.Scanner;
public class Ex01_Array {
public static void main(String[] args) {
// 년도 입력받아 입력 받은 년도의 띠를 구해라
Scanner sc = new Scanner(System.in);
String [] t = {"원숭이","닭","개","돼지","쥐","소","호랑이","용","뱀","말","양"};
//12로 나눴을때 나머지가 0인것이 가장 앞에있는게 편하다.
int year;
String s;
do {
System.out.print("년도 입력");
year = sc.nextInt();
}while(year<1900);
s = t[year%12];
System.out.println(year+" 년도는 "+s+" 띠의 해");
sc.close();
}
}
1차원 배열의 복습
원래는 쥐띠 부터 시작하나 12로 나눴을때 나머지가 0인것이 맨 앞에 오게 하는게 효율적이다.
이러면 나머지가 0이냐 1이냐 등등 에 따라서
배열의 인덱스가 정해진다.
수정) 호랑이와 용사이에 토끼가 들어가야함
5개의 점수 0~10을 입력받아 최대 점수와 최소 점수를 뺀 합을 구해라
package ex0712;
import java.util.Scanner;
public class Ex02_array {
public static void main(String[] args) {
// 5개의 점수 0~10을 입력받아 최대 점수와 최소 점수를 뺀 합을 구해라
Scanner sc = new Scanner(System.in);
int [] score = new int[5];
int max,min;
int tot,result;
tot=0;
for(int i=0; i<score.length; i++) {
do {
System.out.print((i+1)+"번째 점수 : ");
score[i] = sc.nextInt();
}while(score[i]<0 || score[i]>10);
tot += score[i];
}
/*
* 최소 최대값 구하기 또 다른방법 그러나 else if가 좀더 효율적
min = 10; max=0;
for(int i=0; i<score.length; i++){
if(min>score[i]) min=score[i];
if(max<score[i]) max=score[i];
*/
max = min = score[0];
for(int i = 1; i<score.length; i++) {
if(min>score[i]) {
min = score[i];
}
else if(max<score[i]) {
max = score[i];
}
}
result = tot - max - min;
System.out.print("점수 리스트 : ");
for(int n : score) {
System.out.print(n+" ");
}
System.out.println("\n취득 점수 : " + result);
sc.close();
}
}
최소 최대값 구하는 부분을 유심히 보고 실수 하지 않도록 하자.
로또 프로그램
구매 개수가 1~5 사이가 아니면 다시 입력받음
/1~45까지의 서로 다른 6개의 수를 맞혀야함
package ex0712;
import java.util.Scanner;
public class Ex03_lotto {
public static void main(String[] args) {
// 구매 개수가 1~5 사이가 아니면 다시 입력받음
// 1~45까지의 서로 다른 6개의 수를 맞혀야함
Scanner sc = new Scanner(System.in);
int [] lotto = new int[6];
int cnt;
do {
System.out.print("구매 개수는?");
cnt = sc.nextInt();
} while(cnt < 1 || cnt > 5);
for(int i=0; i<=cnt; i++) { //구매 개수
for(int j=0; j<lotto.length; j++) { //한 게임당 6번 반복
lotto[j] = (int)(Math.random() * 45)+ 1;
for(int k=0; k<j; k++) { //중복 수 발생하면 다시 추출
if(lotto[j] == lotto[k]) {
j--;
break;
}
}
}
System.out.print(i+"번째 : ");
for(int n : lotto) {
System.out.print(n+" ");
}
System.out.println();
}
sc.close();
}
}
정렬
Selection Sort
선택 정렬
package ex0712;
public class Ex04_selection {
public static void main(String[] args) {
// Selection Sort
int [] num = new int[] {25,15,10,5,12,9,17,23,13,19};
int t;
System.out.print("Source data : ");
for(int n : num) {
System.out.printf("%5d",n);
}
System.out.println();
//정렬
for(int i = 0; i<num.length-1; i++) { // 회전
for(int j=i+1; j<num.length; j++) {
if(num[i] > num[j]) {
t = num[i];
num[i] = num[j];
num[j] = t;
}
}
}
System.out.print("Sort data : ");
for(int n : num) {
System.out.printf("%5d",n);
}
System.out.println();
}
}
bubble sort
package ex0712;
public class Ex06_bubble {
public static void main(String[] args) {
// bubble sort
int [] num = {25,15,10,5,12,9,17,23,13,19};
int t;
System.out.print("Source data : ");
for(int i =0; i<num.length; i++) {
System.out.printf("%5d", num[i]);
}
System.out.println();
//정렬
// 1회전 : 0:1 / 1:2 / 2:3 ... ... ... 8:9
// 2회전 : 0:1 / 1:2 / 2:3 ... ... 7:8
// 3회전 : 0:1 / 1:2 / 2:3 ... 6:7
// 9회전 : 0:1
for(int i=1; i<num.length; i++) { //1~9 9회전 시켜야함
for(int j=0; j<num.length-1; j++) { //i=1,j=0~8 / i=2,j=0~7
if(num[j] > num[j+1]) {
t=num[j];
num[j]=num[j+1];
num[j+1]=t;
}
}
}
System.out.print("Sort data : ");
for(int i=0; i<num.length; i++) {
System.out.printf("%5d", num[i]);
}
System.out.println();
}
}
개선된 bubble sort
package ex0712;
import java.util.Arrays;
public class Ex07_bubblesort {
public static void main(String[] args) {
// 개선된 bubble sort
int [] num = new int[] {10,20,15,30,35,45,50,60,55,53};
int t, pass;
boolean b;
System.out.println("source data : ");
for(int i=0; i<num.length; i++) {
System.out.printf("%5d", num[i]);
}
System.out.println();
pass=1;
do {
b=false;
for(int i=0; i<num.length-pass; i++) {
if(num[i] > num[i+1]) {
t = num[i]; num[i] = num[i+1]; num[i+1] = t;
b = true;
}
}
System.out.println(pass + "회전 : "+ Arrays.toString(num));
pass++;
}while(b);
System.out.println("sort data : ");
for(int i=0; i<num.length; i++) {
System.out.printf("%5d", num[i]);
}
System.out.println();
}
}
각 정렬 별 시간 비교
package ex0712;
import java.util.Arrays;
public class Ex08_sortTime {
public static void main(String[] args) {
// 정렬 시간 비교
int []a = new int[1000];
int []b = new int[1000];
int []c = new int[1000];
int n, t;
long start, end;
for(int i=0; i<a.length; i++) {
n = (int)(Math.random()*1000)+1;
a[i] = n; b[i] = n; c[i] = n;
}
//System.out.println("source : " + Arrays.toString(a));
// Arrays.sort()를 이용한 정렬
start = System.nanoTime(); //현재 컴퓨터 시간을 nano time 으로 반환
Arrays.sort(a);
end = System.nanoTime();
System.out.println("Arrays sort() : " + (end-start));
//System.out.println("sort : " + Arrays.toString(a));
//selection sort
start = System.nanoTime();
for(int i=0; i<b.length-1; i++) {
for(int j=i+1; j<b.length; j++) {
if(b[i] > b[j]) {
t=b[i]; b[i]=b[j]; b[j]=t;
}
}
}
end = System.nanoTime();
System.out.println("selection sort() : " + (end-start));
//bubble sort
/*
int pass=1;
boolean flag;
start = System.nanoTime();
do {
flag = false;
for(int i=0; i<c.length-pass; i++) {
if(c[i] > c[i+1]) {
t = c[i]; c[i]=c[i+1]; c[i+1]=t;
flag = true;
}
}
pass++;
}while(flag);
end = System.nanoTime();
System.out.println("bubble sort() : " + (end-start));
*/
//향상된 버블
boolean flag=true;
start = System.nanoTime();
for(int i=1; flag; i++) {
flag = false;
for(int j=0; j<c.length-i; j++) {
if(c[j] > c[j+1]) {
t = c[j]; c[j]=c[j+1]; c[j+1]=t;
flag = true;
}
}
}
end = System.nanoTime();
System.out.println("bubble sort() : " + (end-start));
}
}
Insertion sort
package ex0712;
public class Ex09_insertion {
public static void main(String[] args) {
// Insertion sort
int [] num = {25,15,7,5,13,10,17,16,23,12};
int i,j,key;
System.out.print("source data : ");
for(int n : num) {
System.out.printf("%5d",n);
}
System.out.println();
for(i=1; i<num.length; i++) {
key = num[i];
for(j = i-1; j>=0; j--) {
if(key < num[j]) {
num[j+1] = num[j];
}else {
break;
}
}
num[j+1] = key;
}
System.out.print("sort data : ");
for(int n : num) {
System.out.printf("%5d",n);
}
System.out.println();
}
}
2차원 배열 선언과 행 열 길이
package ex0712;
public class Ex10_array2 {
public static void main(String[] args) {
// 2차원 배열 선언과 행 열 길이
int [][]a = new int[2][4];
int [][]b = new int[3][];
b[0] = new int[3];
b[1] = new int[2];
b[2] = new int[4];
System.out.println(a.length);
System.out.println(a[0].length);
System.out.println(a[1].length);
System.out.println(b.length);
System.out.println(b[0].length);
System.out.println(b[1].length);
System.out.println(b[2].length);
}
}
2차원 배열 한줄에 만들기
package ex0712;
public class Ex11_array2 {
public static void main(String[] args) {
// 2차원 배열 한줄에 만들기
int [][]a = new int[][] {{1,2,3},{4,5,6}};
System.out.println(a[0][1]);
System.out.println(a[1][2]);
}
}
2차원 배열을 이용해서 1~20까지 수 나열 (행 우선)
package ex0712;
public class Ex12_array2 {
public static void main(String[] args) {
// 2차원 배열을 이용해서 1~20까지 수 나열 (행 우선)
int [][]a = new int[5][4];
int n = 0;
for(int i =0; i<a.length; i++) {
for(int j=0; j<a[i].length; j++) {
n++;
a[i][j] = n;
}
}
for(int i=0; i<a.length; i++) {
for(int j=0; j<a[i].length; j++) {
System.out.printf("%3d",a[i][j]);
}
System.out.println();
}
System.out.println(a.length);
}
}
2차원 배열 1~20까지 수 나열 (열 우선)
package ex0712;
public class Ex13_array2 {
public static void main(String[] args) {
// 2차원 배열 1~20까지 수 나열 (열 우선)
int [][]a = new int[5][4];
int n = 0;
for(int i =0; i<4; i++) { // 열 - a[0].length = 4
for(int j=0; j<5; j++) { //행 - a.length = 5
n++;
a[j][i] = n;
}
}
for(int i=0; i<a.length; i++) {
for(int j=0; j<a[i].length; j++) {
System.out.printf("%3d",a[i][j]);
}
System.out.println();
}
System.out.println(a.length);
}
}
열 우선 정렬이 좀 더 어렵다.
i와 j가 바뀌는거 확인
5*4 배열에 1~100사이의 난수를 대입하고 4*5로 변환
package ex0712;
public class Ex14_array2 {
public static void main(String[] args) {
// 5*4 배열에 1~100사이의 난수를 대입하고 4*5로 변환
int [][]a = new int[5][4];
int [][]b = new int[4][5];
for(int i=0; i<a.length; i++) {
for(int j=0; j<a[i].length; j++) {
a[i][j] = (int)(Math.random() * 100) + 1;
}
}
// 5*4 => 4*5로 변환
for(int i=0; i<b.length; i++) {
for(int j=0; j<b[i].length; j++) {
b[i][j] = a[j][i];
}
}
System.out.println("a 배열...");
for(int i=0; i<a.length; i++) {
for(int j=0; j<a[i].length; j++) {
System.out.printf("%4d", a[i][j]);
}
System.out.println();
}
System.out.println("\nb배열");
for(int i=0; i<b.length; i++) {
for(int j=0; j<b[i].length; j++) {
System.out.printf("%4d", b[i][j]);
}
System.out.println();
}
}
}
2차원 배열 초기화
package ex0712;
public class Ex15_array2 {
public static void main(String[] args) {
// 2차원 배열 초기화
int [][]a = new int[][] {{10,20,30},{40,50,60}};
int [][]b = new int[][] {{2,4,6},{1,3},{3,6,9,12}};
System.out.println("a 배열");
for(int i=0; i<a.length; i++) {
for(int j=0; j<a[i].length; j++) {
System.out.printf("%4d", a[i][j]);
}
System.out.println();
}
System.out.println("\nb 배열");
for(int i=0; i<b.length; i++) {
for(int j=0; j<b[i].length; j++) {
System.out.printf("%4d", b[i][j]);
}
System.out.println();
}
}
}
향상된 for문으로 2차원 배열 표시
package ex0712;
public class Ex16_array2 {
public static void main(String[] args) {
// 향상된 for문으로 2차원 배열 표시
int [][]a = {{2,4,6},{10,20,30}};
for(int i = 0; i<a.length; i++) {
for(int j=0; j<a[i].length; j++) {
System.out.printf("%4d", a[i][j]);
}
System.out.println();
}
//향상된 for문으로 바꾸기
for(int []row : a) {
for(int n : row) {
System.out.printf("%4d", n);
}
System.out.println();
}
}
}
이름, 세과목 점수를 입력 받아 총점 및 평균, 석차 계산
단 인원수를 입력 받아 입력 받은 인원수만큼 처리
package ex0712;
import java.util.Scanner;
public class Ex17_score {
public static void main(String[] args) {
// 이름, 세과목 점수를 입력 받아 총점 및 평균, 석차 계산
// 단 인원수를 입력 받아 입력 받은 인원수만큼 처리
Scanner sc = new Scanner(System.in);
int cnt;
do {
System.out.print("인원수는?");
cnt = sc.nextInt();
} while(cnt<1);
String []name = new String[cnt];
int [][] score = new int[cnt][3];
int []tot = new int[cnt];
int []rank = new int[cnt];
String[] title = new String[] {"국어 ?","영어 ?","수학 ?"};
//인원수 만큼 이름,국영수를 입력 받아 총점 계산.
for(int i=0; i<cnt; i++) {
System.out.print((i+1)+"번째 이름 ?");
name[i] = sc.next();
for(int j=0; j<score[i].length; j++) {
System.out.print(title[j]);
score[i][j] = sc.nextInt(); // 각 과목별 점수 입력
tot[i] += score[i][j]; //개인 총점 계산
}
}
// 석차 초기값 1로
for(int i=0; i<rank.length; i++) {
rank[i] = 1;
}
// 석차 계산
for(int i=0; i<cnt-1; i++) {
for(int j=i+1; j<cnt; j++) {
if(tot[i] > tot[j]) {
rank[j]++;
} else if(tot[j] < tot[i]) {
rank[i]++;
}
}
}
System.out.println("\n이름\t국어\t영어\t수학\t총점\t평균\t석차");
for(int i=0; i<cnt; i++) {
System.out.print(name[i] + "\t");
for(int j=0; j<score[i].length; j++) {
System.out.print(score[i][j] + "\t");
}
System.out.print(tot[i] + "\t");
System.out.print((tot[i]/3) + "\t");
System.out.println(rank[i]);
}
sc.close();
}
}
문제 1
package ex0712;
public class Ex18_Q1 {
public static void main(String[] args) {
// 5행 5열의 배열에 1~26까지의 수를 ㄹ자 모양으로 채워 넣어라
int [][]a = new int[5][5];
int n = 0;
for(int i=0; i<5; i++) {
for(int j=0; j<5; j++) {
n++;
if(i%2==0) {
a[i][j] = n;
} else {
a[i][4-j] = n;
}
}
}
for(int i=0; i<a.length; i++) {
for(int j=0; j<a[i].length; j++) {
System.out.printf("%3d",a[i][j]);
}
System.out.println();
}
}
}
문제 2
package ex0712;
public class Ex19_Q2 {
public static void main(String[] args) {
// 예제 문제2
char[][] c = new char[5][5];
char n = 'A';
for(int i=0; i<5; i++) {
for(int j=4; j>=0; j--) {
c[j][i] = n++;
}
}
for(int i=0; i<c.length; i++) {
for(int j=0; j<c[i].length; j++) {
System.out.printf("%3c", c[i][j]);
}
System.out.println();
}
}
}
반응형